採用redis token,分佈式鎖的接口冪等性實現

每一次進行冪等校驗以前先獲取token,由於token的時效性只有1次,咱們每次得到的token在冪等操做後就無效了,因此一個token不須要長期保存在redis中。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操做執行完畢後釋放分佈式鎖,見postHandleapp

分佈式鎖的具體實現爲dom

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 = "EX";
@Autowired
private JedisPool jedisPool;

public <T> T execute(RedisFunction<T, Jedis> 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<T, E> {

    Object callback(E jedis);
}

最後解釋一下爲何在分佈式鎖中不直接使用setnx+expire來設置分佈式鎖,而使用set(key,value,"NX","PX",過時時間)來作分佈式鎖,由於你鬼知道它在執行setnx的時候是否是恰好系統崩潰了,這樣expire就未執行,結果你們都清楚這個分佈式鎖就永遠鎖定了。ide

相關文章
相關標籤/搜索