SpringBoot 整合 Redis

本文涉及的产品
云数据库 Redis 版,标准版 2GB
推荐场景:
搭建游戏排行榜
云原生内存数据库 Tair,内存型 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
目录
相关文章
|
24天前
|
缓存 NoSQL Java
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解分布式情况下如何添加分布式锁 【续篇】
这篇文章是关于如何在SpringBoot应用中整合Redis并处理分布式场景下的缓存问题,包括缓存穿透、缓存雪崩和缓存击穿。文章详细讨论了在分布式情况下如何添加分布式锁来解决缓存击穿问题,提供了加锁和解锁的实现过程,并展示了使用JMeter进行压力测试来验证锁机制有效性的方法。
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解分布式情况下如何添加分布式锁 【续篇】
|
13天前
|
编解码 NoSQL Java
使用Spring Boot + Redis 队列实现视频文件上传及FFmpeg转码的技术分享
【8月更文挑战第30天】在当前的互联网应用中,视频内容的处理与分发已成为不可或缺的一部分。对于视频平台而言,高效、稳定地处理用户上传的视频文件,并对其进行转码以适应不同设备的播放需求,是提升用户体验的关键。本文将围绕使用Spring Boot结合Redis队列技术来实现视频文件上传及FFmpeg转码的过程,分享一系列技术干货。
49 3
|
24天前
|
缓存 NoSQL Java
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解、如何添加锁解决缓存击穿问题?分布式情况下如何添加分布式锁
这篇文章介绍了如何在SpringBoot项目中整合Redis,并探讨了缓存穿透、缓存雪崩和缓存击穿的问题以及解决方法。文章还提供了解决缓存击穿问题的加锁示例代码,包括存在问题和问题解决后的版本,并指出了本地锁在分布式情况下的局限性,引出了分布式锁的概念。
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解、如何添加锁解决缓存击穿问题?分布式情况下如何添加分布式锁
|
24天前
|
NoSQL Java Redis
Redis6入门到实战------ 八、Redis与Spring Boot整合
这篇文章详细介绍了如何在Spring Boot项目中整合Redis,包括在`pom.xml`中添加依赖、配置`application.properties`文件、创建配置类以及编写测试类来验证Redis的连接和基本操作。
Redis6入门到实战------ 八、Redis与Spring Boot整合
|
22天前
|
Web App开发 前端开发 关系型数据库
基于SpringBoot+Vue+Redis+Mybatis的商城购物系统 【系统实现+系统源码+答辩PPT】
这篇文章介绍了一个基于SpringBoot+Vue+Redis+Mybatis技术栈开发的商城购物系统,包括系统功能、页面展示、前后端项目结构和核心代码,以及如何获取系统源码和答辩PPT的方法。
|
14天前
|
缓存 NoSQL Java
惊!Spring Boot遇上Redis,竟开启了一场缓存实战的革命!
【8月更文挑战第29天】在互联网时代,数据的高速读写至关重要。Spring Boot凭借简洁高效的特点广受开发者喜爱,而Redis作为高性能内存数据库,在缓存和消息队列领域表现出色。本文通过电商平台商品推荐系统的实战案例,详细介绍如何在Spring Boot项目中整合Redis,提升系统响应速度和用户体验。
41 0
|
18天前
|
缓存 NoSQL Java
【Azure Redis 缓存】定位Java Spring Boot 使用 Jedis 或 Lettuce 无法连接到 Redis的网络连通性步骤
【Azure Redis 缓存】定位Java Spring Boot 使用 Jedis 或 Lettuce 无法连接到 Redis的网络连通性步骤
|
24天前
|
NoSQL JavaScript Java
SpringBoot+Vue+Redis实现验证码功能、一个小时只允许发三次验证码。一次验证码有效期二分钟。SpringBoot整合Redis
这篇文章介绍了如何使用SpringBoot结合Vue和Redis实现验证码功能,包括验证码的有效期控制和一小时内发送次数的限制。
|
27天前
|
存储 NoSQL Java
基于SpringBoot+Redis实现查找附近用户的功能
使用Redis的GEO命令结合SpringBoot实现查找附近用户的功能,通过`GEOADD`命令添加地理位置信息和`GEORADIUS`命令查询附近用户。
47 0
|
27天前
|
存储 NoSQL Redis
基于SpringBoot+Redis实现点赞/排行榜功能,可同理实现收藏/关注功能,可拓展实现共同好友/共同关注/关注推送功能
在SpringBoot项目中使用Redis的Set和ZSet集合实现点赞和排行榜功能,并通过示例代码展示了如何使用`stringRedisTemplate`操作Redis来完成这些功能。
107 0