采用redis token,分布式锁的接口幂等性实现

每一次进行幂等校验之前先获取token,因为token的时效性只有1次,我们每次获得的token在幂等操作后就无效了,所以一个token不需要长期保存在redis中。
@RestController
public class TokenController {

@Autowired
private RedisService redisService;
@GetMapping("/users-anon/gettoken")
public Map getToken(@RequestParam("url") String url) {
    Map<String,String> tokenMap = new HashMap();
    String tokenValue = UUID.randomUUID().toString();
    tokenMap.put(url + tokenValue, tokenValue);
    redisService.set(url + tokenValue, tokenValue);
    return tokenMap;
}

}
获取token后,访问该url的接口,此时我们使用拦截器进行拦截(/add/**可表示为所有有新增操作的接口)
@SpringBootConfiguration
public class TokenInterceptorConfig extends WebMvcConfigurerAdapter {

@Autowired
private TokenInterceptor tokenInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(tokenInterceptor).addPathPatterns("/add/**");
}

}
拦截器的具体内容为
@Slf4j
@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;
}

直到后续controller操作执行完毕后释放分布式锁,见postHandle。
分布式锁的具体实现为
package com.cloud.user.config.redis;

/**

  • 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;

}

}
在RedisServiceImpl实现类中,以上set跟eval的具体实现为
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
@Autowired
private JedisPool jedisPool;

public T execute(RedisFunction fun) {

Jedis jedis = null;
try {
    jedis = jedisPool.getResource();
    return (T)fun.callback(jedis);
}catch (Exception e) {
    logger.error(e.getMessage());
    return null;
}finally {
    if (jedis != null) {
        jedis.close();
    }
}

}
@Override
public String set(String lockKey, String requestId, int expireTime) {

return execute(new RedisFunction<String, Jedis>() {

    @Override
    public String callback(Jedis jedis) {
        return jedis.set(lockKey,requestId,SET_IF_NOT_EXIST,SET_WITH_EXPIRE_TIME,expireTime);
    }

});

}
@Override
public Object eval(String lockKey, String requestId) {

return execute(new RedisFunction<String, Jedis>() {
    @Override
    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));
    }
});

}
public interface RedisFunction {

Object callback(E jedis);

}

上一篇:PHP中MySQL操作


下一篇:C#接口(interface)与类(class)的实例互相转换深度解析