2019独角兽企业重金招聘Python工程师标准>>>
每一次进行幂等校验之前先获取token,因为token的时效性只有1次,我们每次获得的token在幂等操作后就无效了,所以一个token不需要长期保存在redis中。
@RestController 获取token后,访问该url的接口,此时我们使用拦截器进行拦截(/add/**可表示为所有有新增操作的接口) @SpringBootConfiguration 拦截器的具体内容为 @Slf4j 直到后续controller操作执行完毕后释放分布式锁,见postHandle。 分布式锁的具体实现为 package com.cloud.user.config.redis; 在RedisServiceImpl实现类中,以上set跟eval的具体实现为 private static final String SET_IF_NOT_EXIST = "NX"; @Override @Override public interface RedisFunction 最后解释一下为什么在分布式锁中不直接使用setnx+expire来设置分布式锁,而使用set(key,value,"NX","PX",过期时间)来做分布式锁,因为你鬼知道它在执行setnx的时候是不是刚好系统崩溃了,这样expire就未执行,结果大家都清楚这个分布式锁就永远锁定了。
public class TokenController {@Autowired
private RedisService redisService;
@GetMapping("/users-anon/gettoken")public Map getToken(@RequestParam("url") String url) {Map
String tokenValue = UUID.randomUUID().toString();
tokenMap.put(url + tokenValue, tokenValue);
redisService.set(url + tokenValue, tokenValue);
return tokenMap;
}
}
public class TokenInterceptorConfig extends WebMvcConfigurerAdapter {@Autowired
private TokenInterceptor tokenInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(tokenInterceptor).addPathPatterns("/add/**");
}
}
@Component
public class TokenInterceptor implements HandlerInterceptor {@Autowired
private RedisService redisService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String tokenName = request.getRequestURI() + request.getParameter("token_value");
String tokenValue = request.getParameter("token_value");
if (tokenValue != null && !tokenValue.equals("")) {log.info("tokenName:{},tokenValue:{}",tokenName,tokenValue);
return handleToken(request,response,handler);
}return false;
}@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {if (redisService.exists(request.getParameter("token_value"))) {RedisTool.releaseDistributedLock(redisService, request.getParameter("token_value"), request.getParameter("token_value"));
}}@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {}/**
* 分布式锁处理
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
private boolean handleToken(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//当大量高并发下所有带token参数的请求进来时,进行分布式锁定,允许某一台服务器的一个线程进入,锁定时间3分钟
if (RedisTool.tryGetDistributedLock(redisService,request.getParameter("token_value"),request.getParameter("token_value"),180)) {if (redisService.exists(request.getRequestURI() + request.getParameter("token_value"))) {//当请求的url与token与redis中的存储相同时
if (redisService.get(request.getRequestURI() + request.getParameter("token_value")).equals(request.getParameter("token_value"))) {//放行的该线程删除redis中存储的token
redisService.del(request.getRequestURI() + request.getParameter("token_value"));
//放行
return true;
}}//当请求的url与token与redis中的存储不相同时,解除锁定
RedisTool.releaseDistributedLock(redisService,request.getParameter("token_value"),request.getParameter("token_value"));
//进行拦截
return false;
}return false;
}
/**
* Created by Administrator on 2018-08-05.
*/
public class RedisTool {private static final String LOCK_SUCCESS = "OK";
private static final Long RELEASE_SUCCESS = 1L;
/**
* 尝试获取分布式锁
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间
* @return 是否获取成功
*/
public static boolean tryGetDistributedLock(RedisService redisService, String lockKey, String requestId, int expireTime) {String result = redisService.set(lockKey, requestId, expireTime);
if (LOCK_SUCCESS.equals(result)) {return true;
}return false;
}/**
* 释放分布式锁
* @param lockKey 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(RedisService redisService, String lockKey, String requestId) {Object result = redisService.eval(lockKey,requestId);
if (RELEASE_SUCCESS.equals(result)) {return true;
}return false;
}
}
private static final String SET_WITH_EXPIRE_TIME = "PX";
@Autowired
private JedisPool jedisPool;public
}
public String set(String lockKey, String requestId, int expireTime) {return execute(new RedisFunction
public String callback(Jedis jedis) {return jedis.set(lockKey,requestId,SET_IF_NOT_EXIST,SET_WITH_EXPIRE_TIME,expireTime);
}});
}
public Object eval(String lockKey, String requestId) {return execute(new RedisFunction
public Object callback(Jedis jedis) {String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
return jedis.eval(script, Collections.singletonList(lockKey),Collections.singletonList(requestId));
}});
}
}