我正在使用 spring boot 编写我的 rest api.我正在尝试在 redis 服务器上维护用户的会话.Redis 在默认端口 6379 上启动并运行.我已经使用生菜罐连接到 redis 服务器.但似乎我的会话没有在 redis 服务器上设置.我尝试使用 uuid 获取会话对象集,它返回类似这样的内容
I am writing my rest apis using spring boot. And I am trying to maintain user's session on redis server. Redis is up and running on the default port 6379. I have used the lettuce jar to make connection to the redis server. But seems like my session is not being set on redis server. I try to get the session object set using uuid, and it return something like this
127.0.0.1:6379> get 02978830-2f35-47b7-a367-1f48e40d0ea0 (nil)从 redis cli,我可以设置和获取键值.
From redis cli, I am able to set and get the key values.
127.0.0.1:6379> set 123 123dummy OK 127.0.0.1:6379> get 123 "123dummy" 127.0.0.1:6379>这是我尝试查看用户是否已根据其活动会话登录的代码片段,如果会话存在,则返回用户.否则,我正在记录 em,然后在 redis 服务器上设置会话,然后返回用户.
This is code snippet where I am trying to see if the user has been logged in depending on their active session, if the session is there then I am returning user. Else I am logging em and then setting session on redis server and then returning user.
UserAttributes findUserByEmailIdOrPhoneNumber(HttpServletRequest request, @RequestParam(value = "userLoginWay", required = false) String userLoginWay, @RequestParam(value = "userPassword", required = false) String userPassword, @RequestParam(value = "session", required = false) String session) { if(request.getSession().getAttribute(session) != null) { //we have session return user return user; } else { login(userLoginWay, userPassword) //set the session in redis here String sessionUuid = UUID.randomUUID().toString(); request.getSession().setAttribute(sessionUuid, user); return user; } }这个用户是我试图设置为会话值和 uuid 作为键的对象.这就是我尝试连接到 redis 服务器的方式
This user is the object which I am trying to set as a session value and uuid as a key. This is how I am trying to connect to the redis server
@Configuration @EnableRedisHttpSession public class SessionConfig extends AbstractHttpSessionApplicationInitializer { @Bean public LettuceConnectionFactory connectionFactory() { return new LettuceConnectionFactory(); } }这是我在 application.properties
#Configuring Redis server to manage sessions spring.session.store-type=redis spring.redis.host=localhost spring.redis.port=6379知道这有什么问题吗?
推荐答案您必须使用其默认构造函数初始化与 redis 服务器的连接.
You have to initialize the connection with redis server using its default constructor.
return new LettuceConnectionFactory(new RedisStandaloneConfiguration(host, port));您可以使用 @value 从属性文件中获取值,或者更好的方法是使用 @ConfigurationProperties(prefix=spring.redis")
You can get values from properties file using @value or better method is marking the redis @configuration class with @ConfigurationProperties(prefix="spring.redis")
添加字段 String host、int port 以及相应的 getter 和 setter.
add fields String host, int port with respective getters and setters.
更多推荐
在 redis 服务器上设置 spring 会话
发布评论