springboot2.0 通过Redis共享Session避坑指南 - Go语言中文社区

springboot2.0 通过Redis共享Session避坑指南


一、科学导入POM:必须导入以下的包,否则报错。其实整体很简单,就是不要少导包。

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

二、直接上代码

    @RestController
    @RequestMapping(value = "/tst")
    @Slf4j
    @ComponentScan
    @Transactional
    public class TestAPIController {
	    @Autowired
	    private StringRedisTemplate redisClient;
	    @Resource
	    private RedisTemplate<String, Object> redisTemplate;

	    @RequestMapping(value = "/tstRedisClient", method = RequestMethod.GET)
	    @ResponseBody
	    public String tst(String key, String value, HttpServletRequest request) {
	        System.out.println("tstRedisClient");
	        String str = null;
	        List<String> stringList = new ArrayList<>();
	        try {
	
	            //redisClient存取String
	            redisClient.opsForValue().set(key,value);
	            str = redisClient.opsForValue().get(key);
	
	            //使用redisTemplate存取List对象
	            redisTemplate.opsForList().leftPush("stringList","a");
	            redisTemplate.opsForList().leftPush("stringList","b");
	            redisTemplate.opsForList().leftPush("stringList","c");
	            redisTemplate.opsForList().leftPush("message:stringList",stringList1);
	
	            String listValue = redisTemplate.opsForList().index("stringList",1) + "";
	            System.out.println("listValue.1: " + listValue);
	
	
	            //基于Redis存取Session
	            HttpSession session = request.getSession();
	            System.out.println(session.getClass());
	            System.out.println(session.getId());
	            String name = "xiaodafu";
	            session.setAttribute("user",name);
	
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	        }
	        System.out.println("tst2");
	
	        return str;
	    }

三、执行后使用RedisDesktopManager
在这里插入图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/snetlogon20/article/details/101675624
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-02 09:35:08
  • 阅读 ( 973 )
  • 分类:Redis

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢