SpringBoot从小白到精通(七)使用Redis实现高速缓存架构

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: Redis是目前使用最多的缓存,包括Spring Boot 中我们也是会用Redis做很多事情。那么今天就来说一说Spring Boot如何整合Redis。Spring Boot整合Redis 需要那些步骤呢?

前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,

今天主要讲解Springboot整合Redis。Redis是目前使用最多的缓存,包括Spring Boot 中我们也是会用Redis做很多事情。那么今天就来说一说Spring Boot如何整合Redis。Spring Boot整合Redis 需要那些步骤呢?

 

一、整合Redis

新项目整合 Redis 非常容易,只需要创建项目时勾上 Redis 即可,这里就不说了。

我们还是来说说怎么在现有的项目中手动整合Redis:

1、在pom.xml 增加依赖如下

<!-- 引入 redis 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>1.5.7.RELEASE</version>
</dependency>

2、资源文件application.properties中对Redis进行配置

############################################################
#
# REDIS 配置
#
############################################################
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.min-idle=2
spring.redis.timeout=6000


二、封装Redis工具类

这个工具类比较简单,封装操作redisTemplate的实现类。这个工具类只是简单的封装了StringRedisTemplate,其他相关的数据类型大家可以根据自己的需要自行扩展:

package com.weiz.utils;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
/**
 * 
 * @Title: RedisOperator.java
 * @Package com.weiz.util
 * @Description: 使用redisTemplate的操作实现类 Copyright: Copyright (c) 2016
 * 
 * @author weiz
 * @date 2017年9月29日 下午2:25:03
 * @version V1.0
*/
@Component
public class RedisOperator {
// @Autowired
//    private RedisTemplate<String, Object> redisTemplate;
   @Autowired
   private StringRedisTemplate redisTemplate;
   // Key(键),简单的key-value操作
   /**
    * 实现命令:TTL key,以秒为单位,返回给定 key的剩余生存时间(TTL, time to live)。
    * 
    * @param key
    * @return
    */
   public long ttl(String key) {
      return redisTemplate.getExpire(key);
   }
   /**
    * 实现命令:expire 设置过期时间,单位秒
    * 
    * @param key
    * @return
    */
   public void expire(String key, long timeout) {
      redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
   }
   /**
    * 实现命令:INCR key,增加key一次
    * 
    * @param key
    * @return
    */
   public long incr(String key, long delta) {
      return redisTemplate.opsForValue().increment(key, delta);
   }
   /**
    * 实现命令:KEYS pattern,查找所有符合给定模式 pattern的 key
    */
   public Set<String> keys(String pattern) {
      return redisTemplate.keys(pattern);
   }
   /**
    * 实现命令:DEL key,删除一个key
    * 
    * @param key
    */
   public void del(String key) {
      redisTemplate.delete(key);
   }
   // String(字符串)
   /**
    * 实现命令:SET key value,设置一个key-value(将字符串值 value关联到 key)
    * 
    * @param key
    * @param value
    */
   public void set(String key, String value) {
      redisTemplate.opsForValue().set(key, value);
   }
   /**
    * 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
    * 
    * @param key
    * @param value
    * @param timeout
    *            (以秒为单位)
    */
   public void set(String key, String value, long timeout) {
      redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
   }
   /**
    * 实现命令:GET key,返回 key所关联的字符串值。
    * 
    * @param key
    * @return value
    */
   public String get(String key) {
      return (String)redisTemplate.opsForValue().get(key);
   }
   // Hash(哈希表)
   /**
    * 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value
    * 
    * @param key
    * @param field
    * @param value
    */
   public void hset(String key, String field, Object value) {
      redisTemplate.opsForHash().put(key, field, value);
   }
   /**
    * 实现命令:HGET key field,返回哈希表 key中给定域 field的值
    * 
    * @param key
    * @param field
    * @return
    */
   public String hget(String key, String field) {
      return (String) redisTemplate.opsForHash().get(key, field);
   }
   /**
    * 实现命令:HDEL key field [field ...],删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
    * 
    * @param key
    * @param fields
    */
   public void hdel(String key, Object... fields) {
      redisTemplate.opsForHash().delete(key, fields);
   }
   /**
    * 实现命令:HGETALL key,返回哈希表 key中,所有的域和值。
    * 
    * @param key
    * @return
    */
   public Map<Object, Object> hgetall(String key) {
      return redisTemplate.opsForHash().entries(key);
   }
   // List(列表)
   /**
    * 实现命令:LPUSH key value,将一个值 value插入到列表 key的表头
    * 
    * @param key
    * @param value
    * @return 执行 LPUSH命令后,列表的长度。
    */
   public long lpush(String key, String value) {
      return redisTemplate.opsForList().leftPush(key, value);
   }
   /**
    * 实现命令:LPOP key,移除并返回列表 key的头元素。
    * 
    * @param key
    * @return 列表key的头元素。
    */
   public String lpop(String key) {
      return (String)redisTemplate.opsForList().leftPop(key);
   }
   /**
    * 实现命令:RPUSH key value,将一个值 value插入到列表 key的表尾(最右边)。
    * 
    * @param key
    * @param value
    * @return 执行 LPUSH命令后,列表的长度。
    */
   public long rpush(String key, String value) {
      return redisTemplate.opsForList().rightPush(key, value);
   }
}


三、调用Redis缓存操作

创建RedisController控制器,然后分别调用Redis工具类中的get、set等方法。

package com.weiz.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.weiz.utils.JSONResult;
import com.weiz.pojo.SysUser;
import com.weiz.pojo.User;
import com.weiz.utils.JsonUtils;
import com.weiz.utils.RedisOperator;
@RestController
@RequestMapping("redis")
public class RedisController {
    @Autowired
    private StringRedisTemplate strRedis;
    @Autowired
    private RedisOperator redis;
    @RequestMapping("/test")
    public JSONResult test() {
        SysUser user = new SysUser();
        user.setId("100111");
        user.setUsername("spring boot");
        user.setPassword("abc123");
        user.setIsDelete(0);
        user.setRegistTime(new Date());
        strRedis.opsForValue().set("json:user", JsonUtils.objectToJson(user));
        return JSONResult.ok(user);
    }
    @RequestMapping("/getJsonList")
    public JSONResult getJsonList() {
        User user = new User();
        user.setAge(18);
        user.setName("慕课网");
        user.setPassword("123456");
        user.setBirthday(new Date());
        User u1 = new User();
        u1.setAge(19);
        u1.setName("spring boot");
        u1.setPassword("123456");
        u1.setBirthday(new Date());
        User u2 = new User();
        u2.setAge(17);
        u2.setName("hello spring boot");
        u2.setPassword("123456");
        u2.setBirthday(new Date());
        List<User> userList = new ArrayList<>();
        userList.add(user);
        userList.add(u1);
        userList.add(u2);
        redis.set("json:info:userlist", JsonUtils.objectToJson(userList), 2000);
        String userListJson = redis.get("json:info:userlist");
        List<User> userListBorn = JsonUtils.jsonToList(userListJson, User.class);
        return JSONResult.ok(userListBorn);
    }
}

说明:

1. /test 是没有封装的,原生的Redis 客户端操作Redis的方法。

2. /getJsonList 为封装的工具类操作调用方法。

四、验证测试

在浏览器中输入:http://localhost:8080/redis/test  查看是否有数据返回。

image.png

接下来,在redis客户端,输入名:keys *,查看数据是否真的缓存成功。

image.png

 

 


最后

以上,就把Spring Boot 如何整合Redis简单的介绍完了,同时提供了Redis的操作类,这个工具类只是简单的封装了StringRedisTemplate,其他相关的数据类型大家可以根据自己的需要自行扩展。

这个系列课程的完整源码,也会提供给大家。大家关注我的微信公众号(架构师精进),回复:springboot源码。获取这个系列课程的完整源码。



推荐阅读:

Spring Boot从小白到精通(六)使用Mybatis实现增删改查【附详细步骤】

SpringBoot从小白到精通(五)Thymeleaf的语法及常用标签

SpringBoot从小白到精通(四)Thymeleaf页面模板引擎

SpringBoot从小白到精通(三)系统配置及自定义配置

SpringBoot从小白到精通(二)如何返回统一的数据格式

SpringBoot从小白到精通(一)如何快速创建SpringBoot项目

相关实践学习
基于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
相关文章
|
1月前
|
缓存 NoSQL 安全
【Redis】缓存穿透
【Redis】缓存穿透
30 0
|
1月前
|
消息中间件 Cloud Native Java
【Spring云原生系列】SpringBoot+Spring Cloud Stream:消息驱动架构(MDA)解析,实现异步处理与解耦合
【Spring云原生系列】SpringBoot+Spring Cloud Stream:消息驱动架构(MDA)解析,实现异步处理与解耦合
|
1月前
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
1天前
|
前端开发 Java
SpringBoot之三层架构的详细解析
SpringBoot之三层架构的详细解析
7 0
|
7天前
|
缓存 NoSQL Java
使用Redis进行Java缓存策略设计
【4月更文挑战第16天】在高并发Java应用中,Redis作为缓存中间件提升性能。本文探讨如何使用Redis设计缓存策略。Redis是开源内存数据结构存储系统,支持多种数据结构。Java中常用Redis客户端有Jedis和Lettuce。缓存设计遵循一致性、失效、雪崩、穿透和预热原则。常见缓存模式包括Cache-Aside、Read-Through、Write-Through和Write-Behind。示例展示了使用Jedis实现Cache-Aside模式。优化策略包括分布式锁、缓存预热、随机过期时间、限流和降级,以应对缓存挑战。
|
15天前
|
存储 缓存 NoSQL
使用redis进行缓存加速
使用redis进行缓存加速
26 0
|
16天前
|
存储 缓存 NoSQL
Java手撸一个缓存类似Redis
`LocalExpiringCache`是Java实现的一个本地缓存类,使用ConcurrentHashMap存储键值对,并通过ScheduledExecutorService定时清理过期的缓存项。类中包含`put`、`get`、`remove`等方法操作缓存,并有`clearCache`方法来清除过期的缓存条目。初始化时,会注册一个定时任务,每500毫秒检查并清理一次过期缓存。单例模式确保了类的唯一实例。
13 0
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
45 1
|
1月前
|
消息中间件 缓存 Java
SpringBoot的架构学习之路
SpringBoot的架构学习之路
|
1月前
|
存储 缓存 NoSQL
[Redis]——缓存击穿和缓存穿透及解决方案(图解+代码+解释)
[Redis]——缓存击穿和缓存穿透及解决方案(图解+代码+解释)
140 0

热门文章

最新文章