本文主要是介绍Springboot对接企业微信,获取access_tokenjsapi_ticket,实现全局缓存,Sha1加密,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
不善言辞,看得懂就看吧!!!
一、编写配置yml文件
elink: agentid: xxxxxcorpid: xxxxxcorpsecret: XXXXXXXXXXXXXXelinkUrl: 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;@Resourceprivate 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_tokenHttpClient client = HttpClientBuilder.create().build();//构建ClientHttpGet 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_ticketStringBuilder 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**/@Repositorypublic class RedisTokenHelper {@AutowiredStringRedisTemplate stringRedisTemplate;@AutowiredRedisTemplate<Object, Object> redisTemplate;@Resource(name="stringRedisTemplate")ValueOperations<String, String> ops;@Resource(name="redisTemplate")ValueOperations<Object, Object> 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 StringStringBuffer 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@Transactionalpublic class JUnitTest {private final Logger logger = Logger.getRootLogger();@Resourceprivate RedisTokenHelper redisTokenHelper;@Testpublic void test(){String access_token = (String) redisTokenHelper.getObject("access_token");System.out.println("access_token:"+access_token);}}
这篇关于Springboot对接企业微信,获取access_tokenjsapi_ticket,实现全局缓存,Sha1加密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!