spring boot 中redis与cookie整合

在spring boot中整合redis

在已有的spring boot项目的pom中加入redis的依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>

依赖注入后就可以在类中自动装配redis类

 @Autowired
    private RedisTemplate redisTemplate;

redis中设置key value可以选择是否有失效时间

  //设置有失效时间的redis
  //第三个参数设置失效时间数值,第四个参数设置时间单位
  redisTemplate.opsForValue().set(key,value,tokenMaxAge, TimeUnit.SECONDS);

 //设置没有失效时间的redis
 redisTemplate.opsForValue().set(key,value);

对cookie进行封装

public class CookieUtil {

    /**
     * 设置cookie
     * @param response
     * @param name  cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期  以秒为单位
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge){
        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        if(maxAge>0)  cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name){
        Map<String,Cookie> cookieMap = ReadCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }
    }



    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

}

将cookie与redis整合起来

通过用户cookie把用户对应信息存储在redis中

         //生成uuid存放在cookie
        String uuid =RandomUtil.getUUID();

        //添加保存cookie
        CookieUtil.addCookie(response, Constant.Token,uuid,cookieMaxAge);

        //设置有失效时间的redis
        redisTemplate.opsForValue().set(uuid,value,tokenMaxAge, TimeUnit.SECONDS);

通过用户cookie把用户的信息从redis中取出

        //取出cookie
        Cookie cookie= CookieUtil.getCookieByName(request,Constant.Token);

        if(cookie != null) {

            String token = cookie.getValue();

            Object object = redisTemplate.opsForValue().get(token);

            if (object != null) {
                //返回redis中所存的内容
                return (String )object;
            } else {
                return null;
            }
        }else {
            return null;
        }

常用场景:用户登陆,用户产生唯一的标示UUID,将UUID存入cookie,将所对应的信息内容放在UUID对应的redis的中,通过读取用户的UUID来获得用户信息。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用 Spring BootRedis 实现用户登录后用户信息存储以及验证使用 token 的步骤: 1. 首先需要在 pom.xml 添加 Redis 相关的依赖,例如:jedis、spring-boot-starter-data-redis 等。 2. 在 application.properties 文件配置 Redis 相关信息,如下: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 创建一个 UserService 类,用于操作 Redis 存储用户信息和 token。具体包括以下方法: - saveUser(User user):将用户信息存储到 Redis 。 - getUserById(String id):根据用户 id 从 Redis 获取用户信息。 - deleteUserById(String id):根据用户 id 从 Redis 删除用户信息。 - saveToken(String token, String userId):将 token 和用户 id 存储到 Redis 。 - getUserIdByToken(String token):根据 token 从 Redis 获取用户 id。 示例代码如下: ``` @Service public class UserService { @Autowired private StringRedisTemplate redisTemplate; private static final String REDIS_KEY_PREFIX_USER = "user:"; private static final String REDIS_KEY_PREFIX_LOGIN = "login:"; public void saveUser(User user) { String key = REDIS_KEY_PREFIX_USER + user.getId(); redisTemplate.opsForHash().put(key, "id", user.getId()); redisTemplate.opsForHash().put(key, "username", user.getUsername()); redisTemplate.opsForHash().put(key, "password", user.getPassword()); } public User getUserById(String id) { String key = REDIS_KEY_PREFIX_USER + id; String username = (String) redisTemplate.opsForHash().get(key, "username"); String password = (String) redisTemplate.opsForHash().get(key, "password"); User user = new User(); user.setId(id); user.setUsername(username); user.setPassword(password); return user; } public void deleteUserById(String id) { String key = REDIS_KEY_PREFIX_USER + id; redisTemplate.delete(key); } public void saveToken(String token, String userId) { redisTemplate.opsForValue().set(REDIS_KEY_PREFIX_LOGIN + token, userId, Duration.ofMinutes(30)); } public String getUserIdByToken(String token) { return redisTemplate.opsForValue().get(REDIS_KEY_PREFIX_LOGIN + token); } } ``` 4. 在登录接口,验证用户信息是否正确,并将 token 和用户 id 存储到 Redis 。示例代码如下: ``` @RestController public class LoginController { @Autowired private UserService userService; @PostMapping("/login") public String login(@RequestBody User user, HttpServletResponse response) { // 验证用户信息是否正确 if (!"admin".equals(user.getUsername()) || !"123456".equals(user.getPassword())) { return "用户名或密码错误"; } // 将 token 和用户 id 存储到 Redis String token = UUID.randomUUID().toString(); userService.saveToken(token, user.getId()); // 将 token 存储到 Cookie Cookie cookie = new Cookie("token", token); cookie.setMaxAge(30 * 60); cookie.setPath("/"); response.addCookie(cookie); return "登录成功"; } } ``` 5. 在需要验证用户信息的接口,从 Redis 获取用户信息,并验证用户是否已登录。示例代码如下: ``` @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public String getUser(@RequestParam String userId, HttpServletRequest request) { // 从 Redis 获取用户信息 User user = userService.getUserById(userId); if (user == null) { return "用户不存在"; } // 验证用户是否已登录 String token = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("token".equals(cookie.getName())) { token = cookie.getValue(); break; } } } if (token == null) { return "用户未登录"; } String loginUserId = userService.getUserIdByToken(token); if (!userId.equals(loginUserId)) { return "用户未登录"; } // TODO:返回用户信息 } } ``` 以上就是使用 Spring BootRedis 实现用户登录后用户信息存储以及验证使用 token 的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值