SpringBoot 整合 Redis

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: SpringBoot整合Redis本实例应用redis做登录及状态检查添加pom依赖<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>application.

SpringBoot整合Redis

本实例应用redis做登录及状态检查

  1. 添加pom依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
  2. 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
  3. 使用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");
    }
    }
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
22天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
78 0
|
1月前
|
消息中间件 NoSQL Java
springboot redis 实现消息队列
springboot redis 实现消息队列
37 1
|
27天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
189 0
|
6天前
|
NoSQL 数据可视化 Java
Springboot整合redis
Springboot整合redis
|
6天前
|
人工智能 前端开发 Java
Java语言开发的AI智慧导诊系统源码springboot+redis 3D互联网智导诊系统源码
智慧导诊解决盲目就诊问题,减轻分诊工作压力。降低挂错号比例,优化就诊流程,有效提高线上线下医疗机构接诊效率。可通过人体画像选择症状部位,了解对应病症信息和推荐就医科室。
49 10
|
16天前
|
NoSQL Java Redis
Springboot整合redis
Springboot整合redis
|
23天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
48 1
|
1月前
|
缓存 NoSQL Java
springboot中集成redis,二次封装成工具类
springboot中集成redis,二次封装成工具类
172 0
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
46 1
|
1月前
|
监控 NoSQL Java
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】