hutool实现本地锁,本地token功能

发布时间:2024年01月18日

实现本地锁,本地token功能? 。

put()时设置的时间比定义时设置的时间优先级高。

package com.navigation.berth.common.util;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.thread.ThreadUtil;
import com.navigation.berth.entity.SysUser;


/**
 * @author dll
 */
public class LocalCache {
    // 超过一分钟缓存自动删除
    public static final TimedCache<String, String> LOCK = CacheUtil.newTimedCache(1000*3);

    public static final long TOKEN_ACTION_TIME = 24*60*60*1000;

    // 超过1天缓存自动删除
    public static final TimedCache<String, SysUser> TOKENS = CacheUtil.newTimedCache(TOKEN_ACTION_TIME);

    static {
        /** 每100ms检查一次过期 */
        LOCK.schedulePrune(100);
        /** 每10秒检查一次过期 */
        TOKENS.schedulePrune(10000);
    }

    /**
     * 存入键值对,提供消逝时间
     *
     * @param key
     * @param value
     * @param timeout
     */
    public static void put(TimedCache<String, String>  cache,String key, String value, Long timeout) {
        /** 设置消逝时间 */
        cache.put(key, value, timeout);
    }

    /**
     * 每次重新get一次缓存,均会重新刷新消逝时间
     *
     * @param key
     * @return
     */
    public static String get(TimedCache<String, String>  cache,String key) {
        return cache.get(key);
    }


    public static void setToken(String key, SysUser value) {
        TOKENS.put(key, value ,TOKEN_ACTION_TIME);
    }

    public static SysUser getToken(String key) {
        return TOKENS.get(key);
    }



    // 数据锁
    public static synchronized  boolean lock(String key, String value, Long timeout) {
            if (LOCK.containsKey(key)) {
                return false;
            } else {
                LocalCache.put(LOCK,key, "1", timeout);
            }

        return true;
    }


// 用ReentrantLock实现
//    static Lock rtLock = new ReentrantLock();
//    public static boolean lock(String key, String value, Long timeout) {
//        if (rtLock.tryLock()) {
//            try {
//                if (LOCK.containsKey(key)) {
//                    return false;
//                } else {
//                    LocalCache.put(LOCK, key, "1", timeout);
//                    return true;
//                }
//            } finally {
//                rtLock.unlock();
//            }
//        } else {
//            return false;
//        }
//    }



    public static void unLock(String key) {
        LOCK.remove(key);
    }


    public static void main(String[] args) {
//        put(LOCK,"haha", "1", 3000L);
        LOCK.put("haha", "1",2000L);
        ThreadUtil.sleep(2000);
        if (LOCK.containsKey("haha")) {
            System.out.println("aa");
        }
        System.out.println("第1次结果:" + get(LOCK,"haha"));
        ThreadUtil.sleep(2000);
        System.out.println("第2次结果:" + get(LOCK,"haha"));
        ThreadUtil.sleep(3000);
        System.out.println("第3次结果:" + get(LOCK,"haha"));
        if (LOCK.containsKey("haha")) {
            System.out.println("aa");
        }
//        // 取消定时清理
//        LOCK.cancelPruneSchedule();

//        Thread ta = new Thread(() -> {
//            System.out.println(lock("haha", "1", 3000L));
//        });
//
//        Thread tb = new Thread(() -> {
//            System.out.println(lock("haha", "1", 3000L));
//        });
//
//        ta.start();
        ThreadUtil.sleep(10);
//        tb.start();

    }

}

login 方法

        @ApiOperation(value = "登录接口", notes = "登录接口")
        @PostMapping(value="/login")
        public Result login(@RequestBody SysUser sysUser, HttpServletRequest request){
                SysUser user = sysUserService.lambdaQuery().eq(SysUser::getUserName,sysUser.getUserName()).one();
                Assert.notNull(user,"账号不存在");
                Assert.equals(user.getUserPwd(),DigestUtil.md5Hex(sysUser.getUserPwd()),"密码错误");
//                request.getSession().setAttribute("user",user);

                Map map = new HashMap<>();
                String token = UUID.randomUUID().toString();
                LocalCache.setToken(token,user);
                map.put("token",token);
                return  Result.ok(map);
        }

文章来源:https://blog.csdn.net/daizikui/article/details/135670870
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。