Ver código fonte

微信公众号token使用redis做缓存处理

jk-GitHub-coder 4 anos atrás
pai
commit
12be286629

+ 6 - 0
YijiaRestful/pom.xml

@@ -21,6 +21,12 @@
 
     <dependencies>
 
+        <!-- redis 缓存操作 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+
         <!-- WxJava公众号 -->
         <dependency>
             <groupId>com.github.binarywang</groupId>

+ 46 - 0
YijiaRestful/src/main/java/com/platform/yijia/config/RedisConfig.java

@@ -0,0 +1,46 @@
+package com.platform.yijia.config;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+/**
+ * redis配置
+ * @author JK
+ * @date 2021年3月2日
+ */
+@Configuration
+public class RedisConfig{
+
+    @Bean
+    @SuppressWarnings("all")
+    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
+
+        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
+        template.setConnectionFactory(factory);
+        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
+        ObjectMapper om = new ObjectMapper();
+        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+        jackson2JsonRedisSerializer.setObjectMapper(om);
+        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
+
+        // key采用String的序列化方式
+        template.setKeySerializer(stringRedisSerializer);
+        // hash的key也采用String的序列化方式
+        template.setHashKeySerializer(stringRedisSerializer);
+        // value序列化方式采用jackson
+        template.setValueSerializer(jackson2JsonRedisSerializer);
+        // hash的value序列化方式采用jackson
+        template.setHashValueSerializer(jackson2JsonRedisSerializer);
+        template.afterPropertiesSet();
+        return template;
+    }
+
+}

+ 60 - 10
YijiaRestful/src/main/java/com/platform/yijia/controller/IntegralShoppingMallController.java

@@ -5,6 +5,15 @@ import com.platform.yijia.pojo.*;
 import com.platform.yijia.service.*;
 import com.platform.yijia.utils.CodeMsg;
 import com.platform.yijia.utils.ResultData;
+import com.platform.yijia.utils.redis.RedisCacheUtil;
+import com.platform.yijia.utils.weixinapp.WeiXinUserUtil;
+import com.platform.yijia.utils.weixinapp.WxPushUtil;
+import me.chanjar.weixin.common.error.WxErrorException;
+import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
+import me.chanjar.weixin.mp.api.WxMpService;
+import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
+import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
+import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -14,10 +23,9 @@ import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import java.math.BigDecimal;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
 
 /*
  * <Title> IntegralShoppingMallController </Title>
@@ -39,6 +47,10 @@ public class IntegralShoppingMallController {
     private StationService stationService;
     @Resource
     private CustomerPointsRecordService customerPointsRecordService;
+    @Resource
+    private RedisCacheUtil redisCacheUtil;
+    @Resource
+    private WxPushUtil wxPushUtil;
 
     //获取油站积分商品信息
     @RequestMapping(value = "/getIntegralWaresInfoList", method = RequestMethod.GET)
@@ -107,15 +119,18 @@ public class IntegralShoppingMallController {
         for(int i=0; i<6; i++){
             str+=random.nextInt(10);
         }
-        integralOrder.setIntegralOrderNo(System.nanoTime()+str);
+        String integralOrderNo = System.nanoTime()+str;
+        integralOrder.setIntegralOrderNo(integralOrderNo);
         integralOrder.setExchangeTime(new Date());
 
         //更新用户积分
+        String surplusPoints ="";   //剩余积分
         CustomerPoints customerPointsInfo = customerPointsService.getCustomerPointsInfo(customerPoints);
         if(customerPointsInfo !=null){
             //用户剩余积分
             BigDecimal points = new BigDecimal(customerPointsInfo.getPoints()).subtract(new BigDecimal(request.getIntegral()));
-            customerPoints.setPoints(Integer.valueOf(points.toString()));
+            surplusPoints = points.toString();
+            customerPoints.setPoints(Integer.valueOf(surplusPoints));
             //用户已消费积分累积
             BigDecimal consumptionPoints = new BigDecimal(customerPointsInfo.getConsumptionPoints()).add(new BigDecimal(request.getIntegral()));
             customerPoints.setConsumptionPoints(Integer.valueOf(consumptionPoints.toString()));
@@ -123,10 +138,16 @@ public class IntegralShoppingMallController {
         }
 
         //油站名称
+        String gzhAppId ="";
+        String gzhAppSecret ="";
+        String stationName = "";
         Map<String, String> m = stationService.getStationAppIdAndAppSecret(request.getStationId());
-        if(m !=null && m.containsKey("stationName")){
-            integralOrder.setStationName(m.get("stationName"));
-            customerPointsRecord.setStationName(m.get("stationName"));
+        if(m !=null && m.containsKey("stationName") && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
+            stationName = m.get("stationName");
+            gzhAppId = m.get("gzhAppId");
+            gzhAppSecret = m.get("gzhAppSecret");
+            integralOrder.setStationName(stationName);
+            customerPointsRecord.setStationName(stationName);
         }
 
         List<IntegralWares> integralWaresInfoList = integralWaresService.getIntegralWaresInfoList(integralWares);
@@ -142,9 +163,20 @@ public class IntegralShoppingMallController {
         customerPointsRecord.setCreateTime(new Date());
         customerPointsRecordService.insertCustomerPointsInfo(customerPointsRecord);
 
-
         boolean b = integralOrderService.insertIntegralOrder(integralOrder);
         if (b){
+            //公众号积分消耗消息推送
+            List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
+            wxMpTemplate.add(new WxMpTemplateData("first","您好!您已成功在"+stationName+"完成积分商品兑换:"));
+            wxMpTemplate.add(new WxMpTemplateData("keyword1", request.getCustomerName()));
+            wxMpTemplate.add(new WxMpTemplateData("keyword2", integralOrderNo));
+            wxMpTemplate.add(new WxMpTemplateData("keyword3", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
+            wxMpTemplate.add(new WxMpTemplateData("keyword4", request.getWaresName()));
+            wxMpTemplate.add(new WxMpTemplateData("keyword5", request.getIntegral().toString()));
+            wxMpTemplate.add(new WxMpTemplateData("remark",
+                    "截止至" + new SimpleDateFormat(" yyyy年MM月dd日HH时mm分").format(new Date())+",您在"+stationName+"的当前积分值还剩余 "+surplusPoints+" 分."));
+            String templateId = "9EWrreI-P8r4xDgoOcczC4jHt1v0HEjKzkgVRDzoNXA";  //积分兑换成功通知
+            wxPushUtil.push(gzhAppId, gzhAppSecret, templateId, request.getOpenId(), wxMpTemplate);
             resultData=ResultData.success(CodeMsg.SUCCESS);
         }else {
             resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
@@ -152,6 +184,23 @@ public class IntegralShoppingMallController {
         return gson.toJson(resultData);
     }
 
+    //测试redis缓存
+    @RequestMapping(value = "/redisCacheUtil", method = RequestMethod.GET)
+    @ResponseBody
+    public String redisCacheUtil(@RequestParam String unionId){
+        Gson gson =new Gson();
+        //返回结果集
+        ResultData resultData = null;
+        if(unionId !=null){
+            redisCacheUtil.setCacheObject("unionId", unionId);
+            String cacheObject = redisCacheUtil.getCacheObject("unionId");
+            resultData=ResultData.success(cacheObject);
+        }else {
+            resultData=ResultData.success(CodeMsg.REQUEST_FAIL);
+        }
+        return gson.toJson(resultData);
+    }
+
     //获取用户积分订单列表
     @RequestMapping(value = "/getUserIntegralOrderList", method = RequestMethod.GET)
     @ResponseBody
@@ -208,4 +257,5 @@ public class IntegralShoppingMallController {
         }
         return gson.toJson(resultData);
     }
+
 }

+ 1 - 0
YijiaRestful/src/main/java/com/platform/yijia/pojo/IntegralOrder.java

@@ -15,6 +15,7 @@ public class IntegralOrder {
     private  String waresName;           //'商品名称',
     private  Integer waresId;           //'商品名称',
     private  String unionId;             //'微信唯一标识',
+    private  String openId;             //'公众号ID',
     private  String customerName;        //'会员名称',
     private  Integer exchangeNum;        //'兑换数量',
     private  Date exchangeTime;          //'兑换时间',

+ 220 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/redis/RedisCacheUtil.java

@@ -0,0 +1,220 @@
+package com.platform.yijia.utils.redis;
+
+import org.springframework.data.redis.core.HashOperations;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * spring redis 工具类
+ * @author JK
+ * @date 2021年3月2日
+ */
+@Component
+public class RedisCacheUtil
+{
+    @Resource
+    private RedisTemplate redisTemplate;
+
+    /*
+     * 缓存基本的对象,Integer、String、实体类等
+     * @param key 缓存的键值
+     * @param value 缓存的值
+     */
+    public  <T> void setCacheObject(final String key, final T value)
+    {
+        redisTemplate.opsForValue().set(key, value);
+    }
+
+    /*
+     * 缓存基本的对象,Integer、String、实体类等
+     * @param key 缓存的键值
+     * @param value 缓存的值
+     * @param timeout 时间
+     * @param timeUnit 时间颗粒度
+     */
+    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
+    {
+        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
+    }
+
+    /*
+     * 判断缓存中是否存在
+     * @param key
+     * @return
+     */
+    public boolean hasKey(final String key){
+        Boolean b = redisTemplate.hasKey(key);
+        return b;
+    }
+
+    /*
+     * 设置有效时间
+     * @param key Redis键
+     * @param timeout 超时时间
+     * @return true=设置成功;false=设置失败
+     */
+    public boolean expire(final String key, final long timeout)
+    {
+        return expire(key, timeout, TimeUnit.SECONDS);
+    }
+
+    /*
+     * 设置有效时间
+     * @param key Redis键
+     * @param timeout 超时时间
+     * @param unit 时间单位
+     * @return true=设置成功;false=设置失败
+     */
+    public boolean expire(final String key, final long timeout, final TimeUnit unit)
+    {
+        return redisTemplate.expire(key, timeout, unit);
+    }
+
+    /*
+     * 获得缓存的基本对象。
+     * @param key 缓存键值
+     * @return 缓存键值对应的数据
+     */
+    public <T> T getCacheObject(final String key)
+    {
+        ValueOperations<String, T> operation = redisTemplate.opsForValue();
+        return operation.get(key);
+    }
+
+    /*
+     * 删除单个对象
+     * @param key
+     */
+    public boolean deleteObject(final String key)
+    {
+        return redisTemplate.delete(key);
+    }
+
+    /*
+     * 删除集合对象
+     * @param collection 多个对象
+     * @return
+     */
+    public long deleteObject(final Collection collection)
+    {
+        return redisTemplate.delete(collection);
+    }
+
+    /*
+     * 缓存List数据
+     * @param key 缓存的键值
+     * @param dataList 待缓存的List数据
+     * @return 缓存的对象
+     */
+    public <T> long setCacheList(final String key, final List<T> dataList)
+    {
+        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
+        return count == null ? 0 : count;
+    }
+
+    /*
+     * 获得缓存的list对象
+     * @param key 缓存的键值
+     * @return 缓存键值对应的数据
+     */
+    public <T> List<T> getCacheList(final String key)
+    {
+        return redisTemplate.opsForList().range(key, 0, -1);
+    }
+
+    /*
+     * 缓存Set
+     * @param key 缓存键值
+     * @param dataSet 缓存的数据
+     * @return 缓存数据的对象
+     */
+    public <T> long setCacheSet(final String key, final Set<T> dataSet)
+    {
+        Long count = redisTemplate.opsForSet().add(key, dataSet);
+        return count == null ? 0 : count;
+    }
+
+    /*
+     * 获得缓存的set
+     * @param key
+     * @return
+     */
+    public <T> Set<T> getCacheSet(final String key)
+    {
+        return redisTemplate.opsForSet().members(key);
+    }
+
+    /*
+     * 缓存Map
+     * @param key
+     * @param dataMap
+     */
+    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
+    {
+        if (dataMap != null) {
+            redisTemplate.opsForHash().putAll(key, dataMap);
+        }
+    }
+
+    /*
+     * 获得缓存的Map
+     * @param key
+     * @return
+     */
+    public <T> Map<String, T> getCacheMap(final String key)
+    {
+        return redisTemplate.opsForHash().entries(key);
+    }
+
+    /*
+     * 往Hash中存入数据
+     * @param key Redis键
+     * @param hKey Hash键
+     * @param value 值
+     */
+    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
+    {
+        redisTemplate.opsForHash().put(key, hKey, value);
+    }
+
+    /*
+     * 获取Hash中的数据
+     * @param key Redis键
+     * @param hKey Hash键
+     * @return Hash中的对象
+     */
+    public <T> T getCacheMapValue(final String key, final String hKey)
+    {
+        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
+        return opsForHash.get(key, hKey);
+    }
+
+    /*
+     * 获取多个Hash中的数据
+     * @param key Redis键
+     * @param hKeys Hash键集合
+     * @return Hash对象集合
+     */
+    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
+    {
+        return redisTemplate.opsForHash().multiGet(key, hKeys);
+    }
+
+    /*
+     * 获得缓存的基本对象列表
+     * @param pattern 字符串前缀
+     * @return 对象列表
+     */
+    public Collection<String> keys(final String pattern)
+    {
+        return redisTemplate.keys(pattern);
+    }
+}

+ 19 - 3
YijiaRestful/src/main/java/com/platform/yijia/utils/weixinapp/WxPushUtil.java

@@ -1,6 +1,7 @@
 package com.platform.yijia.utils.weixinapp;
 
 
+import com.platform.yijia.utils.redis.RedisCacheUtil;
 import me.chanjar.weixin.common.error.WxErrorException;
 import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
 import me.chanjar.weixin.mp.api.WxMpService;
@@ -9,8 +10,11 @@ import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
 import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
 
+import javax.annotation.Resource;
 import java.util.List;
+import java.util.concurrent.TimeUnit;
 
 /***
  * <Title>  WxPushUtil  </Title>
@@ -18,7 +22,10 @@ import java.util.List;
  * @author JK
  * @date 2021年2月19日
  */
+@Component
 public class WxPushUtil {
+    @Resource
+    private RedisCacheUtil redisCacheUtil;
 
     private static Logger logger =(Logger) LoggerFactory.getLogger(WxPushUtil.class);
 
@@ -36,9 +43,18 @@ public class WxPushUtil {
         WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
         wxMpInMemoryConfigStorage.setAppId(appId);
         wxMpInMemoryConfigStorage.setSecret(appSecret);
-        Token token = WeiXinUserUtil.getToken(appId, appSecret);
-        logger.info("token信息: " + token.getAccessToken());
-        wxMpInMemoryConfigStorage.setAccessToken(token.getAccessToken());
+        //公众号token缓存处理
+        String tokenCache = "";
+        if(!redisCacheUtil.hasKey(appId)){
+            tokenCache = WeiXinUserUtil.getToken(appId, appSecret).getAccessToken();
+            redisCacheUtil.setCacheObject(appId, tokenCache);
+            redisCacheUtil.expire(appId, 7200, TimeUnit.SECONDS);
+            logger.info("Redis缓存中token信息: " + tokenCache);
+        }else {
+            tokenCache = redisCacheUtil.getCacheObject(appId);
+        }
+        logger.info("token信息: " + tokenCache);
+        wxMpInMemoryConfigStorage.setAccessToken(tokenCache);
 
         WxMpService wxMpService = new WxMpServiceImpl();
         wxMpService.setWxMpConfigStorage(wxMpInMemoryConfigStorage);