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

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

    
        org.springframework.boot
        spring-boot-starter-data-redis
    
    
        org.springframework.boot
        spring-session-data-redis
    
    
        org.springframework.session
        spring-session
    
    
        org.springframework.session
        spring-session-data-redis
    

二、直接上代码

    @RestController
    @RequestMapping(value = "/tst")
    @Slf4j
    @ComponentScan
    @Transactional
    public class TestAPIController {
	    @Autowired
	    private StringRedisTemplate redisClient;
	    @Resource
	    private RedisTemplate 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 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
springboot2.0 通过Redis共享Session避坑指南_第1张图片

你可能感兴趣的:(spring,boot,java,redis)