springboot集成spring session

Spring Session & Redis

默认情况下,如果我们使用HttpSession会在内存中保存HttpSession对象,所以当保存的对象多了,便会降低低系统性能,响应缓慢。所以可以考虑,将HttpSession对象的信息保存到redis中,以减少对系统内存的浪费,提高效率。

导包

如果利用spring 生成器生成项目框架
在这里插入图片描述
在这里插入图片描述

配置
package com.springsession.redis.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;

@Configuration
public class redisConfig extends RedisHttpSessionConfiguration {

    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Override
    public void init() {
        //3秒后失效
        setMaxInactiveIntervalInSeconds(3);
    }
}

这里顺便提及一下@EnableRedisHttpSession,如果使用了这个注释,会自动创建一个RedisHttpSessionConfiguration对象。也可以在application.xml中配置spring.session.store-type=redis等效于使用@EnableRedisHttpSession

@EnableRedisHttpSession源码
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({RedisHttpSessionConfiguration.class})
@Configuration(
    proxyBeanMethods = false
)
public @interface EnableRedisHttpSession {
    int maxInactiveIntervalInSeconds() default 1800;

    String redisNamespace() default "spring:session";

    /** @deprecated */
    @Deprecated
    RedisFlushMode redisFlushMode() default RedisFlushMode.ON_SAVE;

    FlushMode flushMode() default FlushMode.ON_SAVE;

    String cleanupCron() default "0 * * * * *";

    SaveMode saveMode() default SaveMode.ON_SET_ATTRIBUTE;
}

测试
 @RequestMapping("/hello")
 public View sayHello(ModelMap model, HttpSession session) {
        String s = (String) session.getAttribute("attrName");
        if (s == null)
            session.setAttribute("attrName","attrValue");
        else 
            System.out.println(s);
        model.addAttribute("id",1);
        return new MappingJackson2JsonView();
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值