SpringBoot整合Redis
本实例应用redis做登录及状态检查
-
添加pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
application.properties配置
#redis spring.redis.database=0 spring.redis.host=111.111.111.111 spring.redis.port=6379 spring.redis.password=root@234 #连接池最大连接数 spring.redis.jedis.pool.max-active=8 #连接池最大阻塞等待时间 默认 -1 表示没有限制 spring.redis.jedis.pool.max-wait=-1ms #连接池最大空闲连接数 spring.redis.jedis.pool.max-idle=8 #连接池最小空闲连接数 spring.redis.jedis.pool.min-idle=0
-
使用redis
- 登录/退出/请求状态监测
/** * @author wsyjlly * @create 2019.06.29 - 12:52 **/ @RestController public class MainController { @Autowired private UserService userService; @Autowired RedisTemplate redisTemplate; @Autowired StringRedisTemplate stringRedisTemplate; /** * 登录信息缓存时长 * */ public static final long EXPIRATION_TIME = 10 * 60; @PostMapping("/status") public ModelMap isLogin(HttpServletRequest request, HttpServletResponse response){ ModelMap map = new ModelMap(); String authorization = request.getHeader("authorization"); if (authorization == ""||authorization == null){ response.setStatus(345); return map.addAttribute("status",false); } String isLogin = stringRedisTemplate.opsForValue().get(authorization); if (null==isLogin){ response.setStatus(345); return map.addAttribute("status",false); } return map.addAttribute("status",true).addAttribute("sa",isLogin); } @PostMapping("/login") public ModelMap login(String username,String password){ ValueOperations<String, String> ops = stringRedisTemplate.opsForValue(); User user = userService.getUser(username, password); if (user!=null) { String token = DigestUtils.sha1DigestAsHex(username + StringUtil.getRandomString(10) + password); if (user.getRole().equals("SuperAdmin")){ ops.set(token, "true", EXPIRATION_TIME, TimeUnit.SECONDS); }else { ops.set(token, "false", EXPIRATION_TIME, TimeUnit.SECONDS); } return new ModelMap().addAttribute("token",token) .addAttribute("result",true) .addAttribute("role",user.getRole()); } return new ModelMap().addAttribute("result",false); } @PostMapping("/logout") public ModelMap logout(HttpServletRequest request){ ValueOperations<String, String> ops = stringRedisTemplate.opsForValue(); System.out.println(request.getHeader("authorization")); Boolean result = ops.getOperations().delete(request.getHeader("authorization")); System.out.println(result); if (result) return new ModelMap().addAttribute("result",true).addAttribute("tip","退出成功!"); return new ModelMap().addAttribute("result",false).addAttribute("tip","退出失败!"); } }
- 拦截器拦截请求并检查状态
/** * @author wsyjlly * @create 2019.06.13 - 16:52 **/ @Controller public class MainInterceptor implements HandlerInterceptor { @Autowired StringRedisTemplate stringRedisTemplate; private Logger logger = LoggerFactory.getLogger(getClass()); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.debug("MainInterceptor...拦截..."+request.getRequestURI()); String authorization = request.getHeader("authorization"); if (authorization == ""||authorization == null){ response.setStatus(345); return false; } Boolean isLogin = stringRedisTemplate.hasKey(authorization); if (!isLogin){ response.setStatus(345); return false; } logger.debug("key是否存在:"+stringRedisTemplate.hasKey(authorization)); logger.debug("key过期时间:"+stringRedisTemplate.getExpire(authorization)); stringRedisTemplate.expire(authorization, MainController.EXPIRATION_TIME, TimeUnit.SECONDS); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.debug("MainInterceptor...postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.debug("MainInterceptor...afterCompletion"); } }