【JAVA基础】Redis使用

Redis使用

redis分布式锁

【Java必备知识点:分布式锁有什么作用?如何实现分布式锁?十分钟用大白话带你彻底搞懂!!】 https://www.bilibili.com/video/BV1TZ421i7wy/?share_source=copy_web&vd_source=55965a967914567042ced99f130f6538

redisHelper使用

https://open.hand-china.com/document-center/doc/component/113/12682?doc_id=11348&_back=%2Fdocument-center%2Fsearch%3Fs%3Dredishelper&doc_code=6204

 @Override
    public ResponseEntity<HtmsResult> depositDeductionRefactor(IfpShipment ifpShipment) {
        IfpShipment tempShipment = ifpShipmentMapper.selectByPrimaryKey(ifpShipment);
        //判断当前运单为‘已支付’,若是则提示:当前状态状态不能进行扣款,若不是则继续
        if ("PAID".equals(tempShipment.getShipmentStatus())) {
            return Results.success(new HtmsResult<>(false, "当前状态状态不能进行扣款"));
        }
        //获取当前运单的redis,若非当前操作人,提示‘redis操作人用户名+正在进行支付,不能扣款’
        String currentOperator = "";
        if (redisHelper.hasKey("htms:shipment:pay-" + tempShipment.getXid())) {
            currentOperator = redisHelper.strGet("htms:shipment:pay-" + tempShipment.getXid());
        }
        if (!DetailsHelper.getUserDetails().getUserId().toString().equals(currentOperator)) {
            return Results.success(new HtmsResult<>(false, currentOperator + "正在进行支付,不能扣款"));
        }
        //获取当前扣款押金
        BigDecimal currentDeposit = ifpShipment.getDeductDepositAmount();
        if (currentDeposit.signum() != 1) {
            return Results.success(new HtmsResult<>(false, currentOperator + "扣款押金应为正数"));
        }
        if (tempShipment.getPodPayCostNotPaid().signum() != 1) {
            return Results.success(new HtmsResult<>(false, currentOperator + "未支付押金应为正数"));
        }
        if (ifpShipment.getId() != null) {
            //校验前端输入的扣款押金值是否小于等于当前运单的 待支付押金
            if (currentDeposit.compareTo(tempShipment.getPodPayCostNotPaid()) == 1) {
                return Results.success(new HtmsResult<>(false, "输入的扣款金额不能大于未支付押金金额"));
            }
            //在redis中记录当前对账单的操作人ID。
            redisHelper.strSet("htms:shipment:pay-" + tempShipment.getXid(), DetailsHelper.getUserDetails().getUserId().toString());

            //前端传入的扣款押金和扣款押金字段原有值相加存入扣款押金字段中,待支付押金减去对应前端传入的扣款押金值。
            if (null == tempShipment.getDeductDepositAmount()) {
                tempShipment.setDeductDepositAmount(BigDecimal.ZERO);
            }
            tempShipment.setDeductDepositAmount(currentDeposit.add(tempShipment.getDeductDepositAmount()));
            if (null == tempShipment.getPodPayCostNotPaid()) {
                tempShipment.setPodPayCostNotPaid(BigDecimal.ZERO);
            }
            tempShipment.setPodPayCostNotPaid(tempShipment.getPodPayCostNotPaid().subtract(currentDeposit));

            //更新运单货主支付状态和平台支付状态为已支付
            //1)货主支付状态更新:判断:total_cost_settle 对账金额(托运方总额)- deduct_deposit_amount 扣除押金金额 = shipper_paid_amount 已支付运费金额(托运方)时更新为已支付,否则判断shipper_paid_amount >0 更新为部分支付,否则为未支付。
            //2)平台支付状态更新:判断:transport_cost_settle  对账金额(司机运费) - deduct_deposit_amount 扣除押金额 = driver_paid_amount 已支付运费金额(平台方),否则判断driver_paid_amount >0 更新为部分支付,否则为未支付。
            if (null == tempShipment.getTotalCostSettle()) {
                tempShipment.setTotalCostSettle(BigDecimal.ZERO);
            }
            if (null == tempShipment.getDeductDepositAmount()) {
                tempShipment.setDeductDepositAmount(BigDecimal.ZERO);
            }
            if (null == tempShipment.getShipperPaidAmount()) {
                tempShipment.setShipperPaidAmount(BigDecimal.ZERO);
            }
            if (null == tempShipment.getTransportCostSettle()) {
                tempShipment.setTransportCostSettle(BigDecimal.ZERO);
            }
            if (null == tempShipment.getDriverPaidAmount()) {
                tempShipment.setDriverPaidAmount(BigDecimal.ZERO);
            }
            if (tempShipment.getTotalCostSettle().subtract(tempShipment.getDeductDepositAmount()).compareTo(tempShipment.getShipperPaidAmount()) == 0) {
                tempShipment.setShipperPayStatus("PAID");
            } else if (tempShipment.getShipperPaidAmount().compareTo(BigDecimal.ZERO) > 0) {
                tempShipment.setShipperPayStatus("PARTIALPAID");
            } else {
                tempShipment.setShipperPayStatus("UNPAID");
            }
            if (tempShipment.getTransportCostSettle().subtract(tempShipment.getDeductDepositAmount()).compareTo(tempShipment.getDriverPaidAmount()) == 0) {
                tempShipment.setDriverPayStatus("PAID");
            } else if (tempShipment.getDriverPaidAmount().compareTo(BigDecimal.ZERO) > 0) {
                tempShipment.setDriverPayStatus("PARTIALPAID");
            } else {
                tempShipment.setDriverPayStatus("UNPAID");
            }
            ifpShipmentMapper.updateByPrimaryKey(tempShipment);

            //将redis中当前对账单的操作人id清空
            redisHelper.delKey("htms:shipment:pay-" + tempShipment.getXid());
        }
        return Results.success(new HtmsResult<>(true, "押金扣款成功!"));
    }

简单汇获取token示例

  @Override
    public String getJdhToken(Long organizationId) throws JsonProcessingException {

        JdhGetTokenDTO jdhGetTokenDTO = new JdhGetTokenDTO();
        IiamJdhCompanyBasic iiamJdhCompanyBasic = new IiamJdhCompanyBasic();
        iiamJdhCompanyBasic.setTenantId(organizationId);
        iiamJdhCompanyBasic = iiamJdhCompanyBasicRepository.selectOne(iiamJdhCompanyBasic);
        if (null == iiamJdhCompanyBasic) {
            throw new CommonException("如需使用综合金融服务,请在门户首页进入工作台,在综合金融服务中完成注册");
        }
        //set data
        requestDataDTO data = new requestDataDTO();
        Long userId = DetailsHelper.getUserDetails().getUserId();
        String phone = iiamJdhUserRepository.selectByPrimaryKey(userId).getPhone();
        IiamJdhCompanyOperator iiamJdhCompanyOperator = new IiamJdhCompanyOperator();
        iiamJdhCompanyOperator.setOperatorMobileNo(phone);
        iiamJdhCompanyOperator = iiamJdhCompanyOperatorRepository.selectOne(iiamJdhCompanyOperator);
        if (null == iiamJdhCompanyOperator) {
            throw new CommonException("您暂无权限访问该内容");
        }
        String jdhUserId = iiamJdhCompanyOperator.getUserId();
        String entCode = iiamJdhCompanyBasic.getJdhEntCode();
        String url = null;
        //1、如果redis中已经记录了token则直接取出。
        if (redisHelper.hasKey("access_token:access_to_jdh"+jdhUserId)){
            String token = redisHelper.strGet("access_token:access_to_jdh"+jdhUserId);
            url = loginUrl + entCode + "&token=" + token;
        }else {
            data.setEntCode(entCode);
            data.setUserId(jdhUserId);
            jdhGetTokenDTO.setData(data);
            //set其它字段
            jdhGetTokenDTO.setPlatformCode("JTWL000001");
            String requestNo = codeRuleBuilder.generateCode("IIAM.JDH.LOGIN", null);
            jdhGetTokenDTO.setRequestNo(requestNo);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String sendDateTime = sdf.format(date);
            jdhGetTokenDTO.setSendDateTime(sendDateTime);

            ObjectMapper mapper = new ObjectMapper();
            String payload = null;
            try {
                payload = mapper.writeValueAsString(jdhGetTokenDTO);
            } catch (JsonProcessingException e) {
                throw new CommonException("Json转化异常", e);
            }
            //生成请求参数
            RequestPayloadDTO requestPayloadDTO = new RequestPayloadDTO();
            requestPayloadDTO.setPayload(payload);
            //接口平台接口调用
            ResponsePayloadDTO responsePayloadDTO = interfaceInvokeSdk.invoke("SRM",
                    "IIAM-JDH-USERLOGIN",
                    "jdhUserLogin",
                    requestPayloadDTO);
            logger.info(String.valueOf(responsePayloadDTO));

            if (responsePayloadDTO != null && "200".equals(responsePayloadDTO.getStatus()) && StringUtils.isNotBlank(responsePayloadDTO.getPayload())) {
                String result = responsePayloadDTO.getPayload();
                JSONObject jsonObject = JSONObject.parseObject(result);
                String tokenJson = jsonObject.getString("respData");
                JSONObject tokenJsonObject = JSONObject.parseObject(tokenJson);
                String newToken = tokenJsonObject.getString("token");
                String respData = jsonObject.getString("respCode");
                String respMsg = jsonObject.getString("respMsg");
                if (!"000000".equals(respData)) {
                    throw new CommonException(respMsg);
                }

                //2、在redis中记录当前操作员token。
                redisHelper.strSet("access_token:access_to_jdh:test"+jdhUserId, newToken, 30, TimeUnit.DAYS );
                url = loginUrl + entCode + "&token=" + newToken;
            }

        }
        return url;
    }

redisTempelete使用


image

/**
     * 支付回调
     */
    @Override
    public String paymentCallback(Map<String, String> params) {
        String errorMessage = "";

        PaymentBasicRequest paymentBasicRequest = new PaymentBasicRequest();
        try {
            org.apache.commons.beanutils.BeanUtils.populate(paymentBasicRequest, params);
        } catch (Exception e) {
            errorMessage = e.getMessage();
        }

        //解密  解析
        String returnMessage = RsaUtil.base64Decode(RsaUtil.decryptByPubCerText(paymentBasicRequest.getSignContent(), paymentConfiguration.getPlatformCerContent()));
        PlaceOrderInfo callBackInfo = JSONObject.parseObject(returnMessage, PlaceOrderInfo.class);

        String generalPaymentNo = callBackInfo.getTransNo();
        if (params.size() > 0) {
            //查redis支付回调记录, 避免重复回调
            if (Boolean.TRUE.equals(this.redisTemplate.hasKey(PAYMENT_PREFIX + generalPaymentNo))) {
                errorMessage = "已在处理";
            } else {
                //打标记
                this.redisTemplate.opsForValue().set(PAYMENT_PREFIX + generalPaymentNo, generalPaymentNo);
                try {
                    //处理查询支付结果
                    if (callBackInfo.getRespMsg() == null) {

                        errorMessage = self().dealWithpaymentCallback(callBackInfo);
                    }
                } catch (Exception e) {
                    errorMessage = e.getMessage();
                } finally {
                    //清除标记
                    this.redisTemplate.delete(PAYMENT_PREFIX + generalPaymentNo);
                }
            }
        }

        return StringUtils.isNotBlank(errorMessage) ? errorMessage : "SUCCESS";
    }

redis开发组件Cache

https://open.hand-china.com/document-center/doc/component/113/15203?doc_id=126723&_back=%2Fdocument-center%2Fsearch%3Fs%3Dredis&doc_code=83532




-DSPRING_REDIS_HOST=redis-d96a042a-2adf-43de-acb9-b032b2ccdfc5.cn-south-1.dcs.myhuaweicloud.com
-DSPRING_REDIS_PASSWORD=Redis@1234

多数据源

事务注解@Transactional

https://open.hand-china.com/community/detail/671035389183660032#@Transactional 注解的属性介绍

posted on 2022-11-10 13:53  舟山婠贞  阅读(12)  评论(0编辑  收藏  举报

导航