分布式应用中session共享

使用redis存储token:

服务端使用UUID生成随机64位或128为token,放入redis中,然后返回给客户端并存储在cookie中,用户每次访问都携带此token,服务端去redis中检验是否有此用户即可

以下是一个基于Spring Boot的示例代码,用于生成随机的UUID token,并将其存储在Redis中,并通过Cookie返回给客户端:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {
    private static final String TOKEN_NAME = "token";
    private static final long TOKEN_EXPIRATION = 3600; // Token过期时间,单位为秒

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String generateToken() {
        String token = UUID.randomUUID().toString();
        String redisKey = getTokenRedisKey(token);
        // 存储token到Redis,并设置过期时间
        redisTemplate.opsForValue().set(redisKey, token, TOKEN_EXPIRATION, TimeUnit.SECONDS);
        return token;
    }

    public boolean verifyToken(HttpServletRequest request) {
        String token = getTokenFromCookie(request);
        if (StringUtils.hasText(token)) {
            String redisKey = getTokenRedisKey(token);
            // 检查Redis中是否存在该token
            return redisTemplate.hasKey(redisKey);
        }
        return false;
    }

    public void setTokenCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(TOKEN_NAME, token);
        cookie.setMaxAge((int) TOKEN_EXPIRATION);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    private String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(TOKEN_NAME)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    private String getTokenRedisKey(String token) {
        return "token:" + token;
    }
}

在这个示例中,TokenService提供了生成和验证Token的方法。在generateToken方法中,使用UUID.randomUUID().toString()生成一个随机的UUID Token,并将其存储在Redis中。在verifyToken方法中,从客户端的Cookie中获取Token,并检查Redis中是否存在该Token。setTokenCookie方法用于将Token设置到响应的Cookie中。

你可以在控制器中使用TokenService来生成和验证Token,示例代码如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String token = tokenService.generateToken();
        tokenService.setTokenCookie(response, token);
        return "Login successful!";
    }

    @GetMapping("/secure")
    public String secure(HttpServletRequest request) {
        if (tokenService.verifyToken(request)) {
            return "Access granted!";
        } else {
            return "Access denied!";
        }
    }
}

/login接口中,生成一个Token,并将其设置到响应的Cookie中。在/secure接口中,验证客户端请求中携带的Token是否有效。

请注意,以上代码仅作为示例,并没有完整的错误

处理和异常处理逻辑。实际应用中,你可能需要根据具体需求进行适当的调整和扩展。此外,还需要确保已正确配置Redis相关的依赖和连接信息。

github代码地址
https://github.com/tanwu001/springboot2.1
代码在p7包中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值