Springboot对接企业微信,获取access_token&jsapi_ticket,实现全局缓存,Sha1加密

不善言辞,看得懂就看吧!!!

一、编写配置yml文件

elink: 
    agentid: xxxxx
    corpid: xxxxx
    corpsecret: XXXXXXXXXXXXXX
    elinkUrl: 127.0.0.1

二、获取access_token&jsapi_ticket写入Redis内存中

通过定时任务实现官网要求的7200秒缓存机制

access_token

@Component
@EnableScheduling
@Slf4j
public class ElinkTokenScheduler{

    @Value("${elink.corpid}")
    private String corpid;
    @Value("${elink.corpsecret}")
    private String corpsecret;
    @Value("${elink.elinkUrl}")
    private String elinkUrl;
    

    @Resource
    private RedisTokenHelper redisTokenHelper;
    /**
     * 定时获取access_token
     * @throws SQLException 
     */
    @Scheduled(fixedDelay=7180000)
    public void getAccessToken() throws SQLException{
        String accessToken = null;
        String jsapiTicket = null;
        StringBuilder urlToken = new StirngBuilder("http://"+elinkUrl+"/cgi-bin/gettoken?");
        urlToken.append("corpid="+corpid); 
        urlToken.append("&corpsecret="+corpsecret);

        try {  
            //获取access_token
            HttpClient client = HttpClientBuilder.create().build();//构建Client
            HttpGet getToken = new HttpGet(urlToken.toString());//构建GET请求
            HttpResponse response = client.execute(getToken);//提交GET请求
            HttpEntity result = response.getEntity();
            String tokenMessage = EntityUtils.toString(result);
            JSONObject tokenJson = JSONObject.parseObject(tokenMessage);
            accessToken = tokenJson.getString("access_token");

            //获取jsapi_ticket
            StringBuilder urlTicket = new StringBuilder("http://"+elinkUrl+"/cgi-bin/get_jsapi_ticket?");
            urlTicket.append("access_token="+accessToken);
            HttpGet getTicket = new HttpGet(urlTicket.toString());//构建GET请求
            response = client.execute(getTicket);//提交GET请求
            result = response.getEntity();
            String ticketMessage = EntityUtils.toString(result);
            JSONObject ticketJson = JSONObject.parseObject(ticketMessage);
            jsapiTicket = tokenJson.getString("ticket");
        } catch (Exception e) {  
                e.printStackTrace();  
        }
        logger.info("==============开始写入access_token&jsapi_ticket===============");
        redisTokenHelper.saveObject("access_token", accessToken);
        redisTokenHelper.saveObject("jsapi_ticket", jsapiTicket);
        logger.info("==============写入access_token&jsapi_ticket成功===============");
    }

}

 三、redis工具类

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

    /**
     * 封装Redis存取Token对的工具类
     * @author spd
     *
     */
    @Repository
    public class RedisTokenHelper {
        @Autowired
        StringRedisTemplate stringRedisTemplate;

        @Autowired
        RedisTemplate redisTemplate;

        @Resource(name="stringRedisTemplate")
        ValueOperations ops;

        @Resource(name="redisTemplate")
        ValueOperations objOps;
        /**
         * 键值对存储 字符串 :有效时间3分钟
         * @param tokenType Token的key
         * @param Token Token的值
         */
        public void save(String tokenType,String Token){
            ops.set(tokenType, Token, 180, TimeUnit.SECONDS);
        }
        /**
         * 根据key从redis获取value 
         * @param tokenType
         * @return String
         */
        public String getToken(String tokenType){
            return ops.get(tokenType);
        }
        /**
         * redis 存储一个对象
         * @param key
         * @param obj
         * @param timeout 过期时间  单位:s
         */
        public void saveObject(String key,Object obj,long timeout){
            objOps.set(key, obj,timeout,TimeUnit.SECONDS);
        }
        /**
         * redis 存储一个对象  ,不过期
         * @param key
         * @param obj
         */
        public void saveObject(String key,Object obj){
            objOps.set(key, obj);
        }
        /**
         * 从redis取出一个对象
         * @param key
         * @param obj
         */
        public Object getObject(String key){
            return objOps.get(key);
        }
        /**
         * 根据Key删除Object
         * @param key
         */
        public void removeObject(String key){
            redisTemplate.delete(key);
        }
    }

四、Sha1的加密方式

public static String SHA1(String decript) {
    try {
        MessageDigest digest = java.security.MessageDigest
                .getInstance("SHA-1");
        digest.update(decript.getBytes());
        byte messageDigest[] = digest.digest();
        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        // 字节数组转换为 十六进制 数
        for (int i = 0; i < messageDigest.length; i++) {
            String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

 

五、JUnit测试获取数据

 

    import org.apache.log4j.Logger;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.SpringApplicationConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.context.web.WebAppConfiguration;
    import org.springframework.transaction.annotation.Transactional;

    import com.bjb.Application;
    import com.bjb.dao.impl.RedisTokenHelper;
    /**
     * Junit单元测试类
     * @author spd
     *
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes=Application.class)
    @WebAppConfiguration
    @Transactional
    public class JUnitTest {
        private final Logger logger = Logger.getRootLogger();

        @Resource
        private RedisTokenHelper redisTokenHelper;

        @Test
        public void test(){
            String access_token = (String) redisTokenHelper.getObject("access_token");
            System.out.println("access_token:"+access_token);
        }
    }

 

Springboot对接企业微信,获取access_token&jsapi_ticket,实现全局缓存,Sha1加密_第1张图片

 

 

你可能感兴趣的:(SpringBoot,redis,缓存)