Redis日记(day05):SpringBoot整合Redis--RedisTemplate操作Redis

636 阅读14分钟

SpringBoot整合Redis--RedisTemplate操作Redis

Spring对Redis的支持一般是实用Jedis操作的,但是SpringBoot对Redis的支持则是使用了自动配置RedisAutoConfiguration中的RedisTemplateStringRedisTemplate,RedisTemplate可以对任何类型的key-value键值对操作。

1、概述

1.1、SpringData

SpringBoot相关的数据操作都被封装到spring-data里面,比如操作整合jdbc mongodb redis!,SpringData 也是和SpringBoot 齐名的项目!以下是 Spring 官网中描述的 SpringData 可以整合的数据源,可以发现 Spring Data Redis

image.png

1.2、lettuce连接池

操作Redis需要的Redis依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- spring2.X集成redis所需的连接池:common-pool2-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.6.0</version>
</dependency>

进入该源码,发现该底层就是依赖的spring-data-redis,并且发现是没有jedis的,原因就是在 SpringBoot2.x 之后,原来使用的jedis被替换为了lettuce,如下

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.6.3</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>2.6.1</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>io.lettuce</groupId>
        <artifactId>lettuce-core</artifactId>
        <version>6.1.6.RELEASE</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

说明: 在 SpringBoot2.x 之后,原来使用的jedis被替换为了lettuce,不可否认,Jedis是一个优秀的基于Java语言的Redis客户端。但是,其不足也很明显

  • jedis: 采用的直连的Redis-Server,在多个线程间共享一个Jedis实例时是线程不安全的,如果想要在多线程场景下使用Jedis,需要使用 jedis pool 连接池! 每个线程都使用自己的Jedis实例,当连接数量增多时,会消耗较多的物理资源,更像 BIO 模式
  • lettuce : Lettuce是一个可伸缩的线程安全的Redis客户端,支持同步、异步和响应式模式。多个线程可以共享一个连接实例,而不必担心多线程并发问题。它基于优秀Netty NIO框架构建,支持Redis的高级功能,如Sentinel,集群,流水线,自动重新连接和Redis数据模型。

2、部分源码简析

2.1、自动配置类RedisAutoConfiguration

SpringBoot所有组件的配置,其中都有一个自动配置类,自动配置类都会绑定一个properties配置文件,以Redis为例,在 spring.factories 中搜索 redis,找到如下图的Redis配置,其中第一个就是自动配置类

image.png

下图就是Redis的自动配置类RedisAutoConfiguration,源码如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.autoconfigure.data.redis;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return new StringRedisTemplate(redisConnectionFactory);
    }
}

从源码注解可以看出,Redis的自动配置类RedisAutoConfiguration绑定了RedisProperties,即Redis对应的配置文件

@EnableConfigurationProperties({RedisProperties.class})

进入其源码,可以发现里面有很多以前缀spring.redis开头的配置,可以在application.yml中配置,配置如host、password等

@ConfigurationProperties(
    prefix = "spring.redis"//配置都是以spring.redis开头

)
public class RedisProperties {
    private int database = 0;  //默认0号数据库
    private String url;   
    private String host = "localhost";  //默认本机地址
    private String username;
    private String password;
    private int port = 6379;
    private boolean ssl;
    private Duration timeout;  //超时等待
    private Duration connectTimeout;
    private String clientName;
    private RedisProperties.ClientType clientType;
    private RedisProperties.Sentinel sentinel;
    private RedisProperties.Cluster cluster;
    private final RedisProperties.Jedis jedis = new RedisProperties.Jedis();
    private final RedisProperties.Lettuce lettuce = new RedisProperties.Lettuce();

    public RedisProperties() {
    }

    public int getDatabase() {
        return this.database;
    }

2.2、RedisTemplate和 StringRedisTemplate

回到 RedisAutoConfiguration,可以看见该配置类里面最后封装了两个Bean,即 redisTemplatestringRedisTemplate

@Bean
//当redisTemplate这个对象不存在时,这个方法才会生效,因此我们可以自己定义一个redisTemplate来替换这个默认的!
@ConditionalOnMissingBean(name = {"redisTemplate"})
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    // 默认的 RedisTemplate 没有过多的设置,redis 对象都是需要序列化!
    // 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换 <String, Object>
    RedisTemplate<Object, Object> template = new RedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    return template; //返回RedisTemplate对象
}

@Bean
@ConditionalOnMissingBean  // 由于 String 是redis中最常使用的类型,所以说单独提出来了一个bean!
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    return new StringRedisTemplate(redisConnectionFactory);//返回StringRedisTemplate对象
}      

两者的关系是StringRedisTemplate继承RedisTemplateRedisTemplate是一个泛型类,而StringRedisTemplate则不是;RedisTemplate可以对任何类型的key-value键值对操作,而StringRedisTemplatekey-value键值都只能是String类型;两者序列化/反序列化不同。

两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。

其实他们两者之间的区别主要在于他们使用的序列化类:

  • RedisTemplate使用的是JdkSerializationRedisSerializer存入数据,会将数据先序列化成字节数组然后在存入Redis数据库。
  • StringRedisTemplate使用的是StringRedisSerializer

使用时注意事项:

  • 当你的redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候,那么你就使用StringRedisTemplate即可。
  • 但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象,那么使用RedisTemplate是更好的选择。
  • 但是大多数情况下都是直接使用RedisTemplate

2.3、RedisConnectionFactory

RedisAutoConfiguration 自动配置类中的 RedisTemplate 方法需要传递一个 RedisConnectionFactory 参数。点进这个参数,源码如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.data.redis.connection;
import org.springframework.dao.support.PersistenceExceptionTranslator;
public interface RedisConnectionFactory extends PersistenceExceptionTranslator {
    RedisConnection getConnection();
    RedisClusterConnection getClusterConnection();
    boolean getConvertPipelineAndTxResults();
    RedisSentinelConnection getSentinelConnection();
}

并查看其实现类,发现有两个实现类,即JedisConnectionFactoryLettuceConnectionFactory

image.png

2.4、JedisConnectionFactory

查看该实现类的源码,如下:

image.png

但是这个类中有很多功能缺失。所以在配置文件中如果配置连接池 Jedis Pool 是不生效的,不建议使用

2.5、LettuceConnectionFactory

查看该实现类的源码,如下:

image.png

都是默认生效,这也说明 SpringBoot 更推荐使用 Lettuce 来配置一些东西,如下:

image.png

3、简单整合使用

3.1、创建SpringBoot初始化工程

新建SpringBoot初始化工程,选择相关依赖

image.png

3.2、依赖

创建好项目以后,整个Pom文件的依赖为:

<dependencies>
    <!-- 操作redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3.3、application.yml 配置

可以配置的组件如下:

# REDIS (Redis 配置)
# 连接工厂使用的数据库索引
spring.redis.database= 0
# Redis服务器主机
spring.redis.host=127.0.0.1
# redis服务器端口
spring.redis.port= 6379
# 登录redis服务器的密码
spring.redis.password=********
# 给定连接池可以分配的最大连接数 使用负值为无限制
spring.redis.lettuce.pool.max-active=20
# 连接分配在池耗尽之前在抛出异常之前应阻止的最大时间量(连接池最大阻塞等待时间以毫秒为单位) 使用负值无限期地阻止
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 使用负值来表示无限数量的空闲连接
spring.redis.lettuce.pool.max-idle=5
# 连接池中的最小空闲连接 此设置只有在正值时才有效果
spring.redis.lettuce.pool.min-idle=0
# 连接超时(毫秒)
spring.redis.timeout=30000

这里配置简单一点,配置连接:application.yml

# 配置 Redis,尽量不要使用jedis.pool配置连接池,推荐使用lettue,默认生效
spring:
  redis:
    host: 192.168.62.130
    port: 6379

3.4、测试

打开springboot的测试类,编写测试代码(使用redisTemplate操作数据)

@SpringBootTest
class Redis02SpringbootApplicationTests{

    // 这就是之前 RedisAutoConfiguration 源码中的 Bean
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {

        /** redisTemplate 操作不同的数据类型,API 和 Redis 中的是一样的
	 * opsForValue 类似于 Redis 中的 String
	 * opsForList 类似于 Redis 中的 List
	 * opsForSet 类似于 Redis 中的 Set
	 * opsForHash 类似于 Redis 中的 Hash
	 * opsForZSet 类似于 Redis 中的 ZSet
	 * opsForGeo 类似于 Redis 中的 Geospatial
	 * opsForHyperLogLog 类似于 Redis 中的 HyperLogLog
	 */

        // 除了基本的操作,常用的命令都可以直接通过redisTemplate操作,比如事务、基本的CRUD……

        // 和数据库相关的操作都需要通过连接操作,获取Redis连接对象
        //RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        //connection.flushDb();
        //connection.flushAll();

       //添加字符串到redis
        redisTemplate.opsForValue().set("key", "呵呵");
        System.out.println(redisTemplate.opsForValue().get("key"));
    }
}

结果:

image.png

然后在终端进行查看:

image.png

发现不是"key"这个键,而是带转义字符的一串序列,原因就是没有进行对应的序列化,并且通过get key命令获取其value值发现也是一串乱码,解决这个问题就需要修改默认的序列化规则。

redisTemplate.opsForValue();  //操作字符串
redisTemplate.opsForHash();  //操作hash
redisTemplate.opsForList();  //操作list
redisTemplate.opsForSet();  //操作set
redisTemplate.opsForZSet();  //操作有序set

4、Redis中的序列化

4.1、源码简析

@ConditionalOnMissingBean(name = {"redisTemplate"})
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    // 默认的 RedisTemplate 没有过多的设置,redis 对象都是需要序列化!
    // 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换 <String, Object>
    RedisTemplate<Object, Object> template = new RedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}

还是RedisTemplate模板,该方法内部创建了一个RedisTemplate对象,进入RedisTemplate类,部分源码如下:

@Nullable
private RedisSerializer keySerializer = null;
@Nullable
private RedisSerializer valueSerializer = null;
@Nullable
private RedisSerializer hashKeySerializer = null;
@Nullable
private RedisSerializer hashValueSerializer = null;

如上,这部分就是Redis相关的默认的序列化配置,继续往下,可以查看到这些序列化对象是在哪赋值的,如下

image.png

可以发现默认的序列化方式是JDK的序列化方式,但我们如果需要的是 JSON 序列化,所以就需要自定义一个配置类。并且在2.1节也说到,当redisTemplate这个对象不存在时,这个方法中的JDK序列化方式才会生效,因此我们可以自己定义一个序列化方式,因此就需要自定义一个配置类来替换这个默认的自动配置类RedisAutoConfiguration!(自定义配置类以后,默认的一切就不会生效,就使用我们自定义的配置类)

4.2、自定义配置类--redisTemplate模板

新建config包,新建RedisConfig类

@Configuration
public class RedisConfig {
    /**
     *  编写自定义的 redisTemplate
     *  这是一个比较固定的模板
     */
    @Bean
    @SuppressWarnings("all")  //镇压所有警告
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        // 为了开发方便,直接使用<String, Object>
        //默认的连接配置,和源码保持一致即可
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);

        // 序列化配置:Json 配置序列化
        // 使用 jackson 解析任意的对象
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 使用 objectMapper 进行转义
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // String 的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // string的key和hash的key都采用string的序列化 
        // value都采用Jackson的序列化

        //key采用string序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // Hash 的 key 采用 String 的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value 采用 jackson 的序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // Hash 的 value 采用 jackson 的序列化方式
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        // 把所有的配置 set 进 template
        template.afterPropertiesSet();

        return template; //最后返回template对象
    }
}

所有的redis操作,其实对于java开发人员来说,十分的简单,更重要是要去理解redis的思想和每一种数据结构的用处和作用场景!

指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

4.3、测试

再次执行contextLoads方法,结果如下:

127.0.0.1:6379> keys *
1) "key"

这次结果就正确显示了

4.4、对象序列化测试

user.java

新建一个User实体类,其实关于对象的保存,不管是String对象还是普通POJO,在实际开发中我们一般不会直接使用对象,而是需要对其进行序列化,一般是序列化成 json字符串。在企业中,我们所有的pojo都会序列化!不过好像在2.0版本,是默认支持序列化的,也就是不需要实现Serializable接口

@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
// 实体类序列化在后面加上 implements Serializable
public class User implements Serializable{
    private String name;
    private int age;
}

测试:


@SpringBootTest
class RedisSpringbootApplicationTests {
    @Autowired
    @Qualifier("redisTemplate")//该注解与自定义的redisTemplate绑定
    private RedisTemplate redisTemplate

@Test
public void test() throws JsonProcessingException {
    User user = new User("皮卡丘",20);
    
        // 使用 JSON 序列化
    //String s = new ObjectMapper().writeValueAsString(user);
       // redisTemplate.opsForValue().set("user", s);
        
    // 这里直接传入一个对象
    redisTemplate.opsForValue().set("user", user);
    System.out.println(redisTemplate.opsForValue().get("user"));
}

结果:

打印结果:

//没有json序列化,从redis中取得的对象
User(name=皮卡丘, age=20) 

//json序列化后,从redis中取得的对象
{"name":"皮卡丘","age":20}

终端查看结果:

127.0.0.1:6379> keys *
1) "key"
2) "user"

127.0.0.1:6379> get user
"\"{\\\"name\\\":\\\"\xe7\x9a\xae\xe5\x8d\xa1\xe4\xb8\x98\\\",\\\"age\\\":20}\""


127.0.0.1:6379> get key
"\"\xe5\x91\xb5\xe5\x91\xb5\""

发现执行成功,没有报错,并且在 Redis 中也没有转义字符了,但是去获取这个对象或者中文字符串的时候还是会显示转义字符,怎么解决?

只需要在启动 Redis 客户端的时候加上 –raw 即可

redis-cli --raw -p 6379

重新执行程序,结果如下:

127.0.0.1:6379> shutdown
not connected> exit
[root@HDU001 bin]# redis-server /etc/redis.conf
[root@HDU001 bin]# redis-cli --raw -p 6379
127.0.0.1:6379> get key
"呵呵"
127.0.0.1:6379> get user
"{\"name\":\"皮卡丘\",\"age\":20}"
127.0.0.1:6379> 

5、工具类RedisUtil

5.1、RedisUtil

但是在企业开发中一般不直接以原生的编写,将常用的操作封装为RedisUtils,自己写一些工具类来使用**,在工具类中应该加入一些容错操作,能抛出异常,在公司能看到一些**封装的RedisUtils: 该工具类封装了使用RedisTemplate操作Redis的所有命令,可以直接使用

@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // =============================common============================
    /**
     * 指定缓存失效时间
     * @param key  键
     * @param time 时间(秒)
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }


    // ============================String=============================

    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 普通缓存放入并设置时间
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 递增
     * @param key   键
     * @param delta 要增加几(大于0)
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }


    /**
     * 递减
     * @param key   键
     * @param delta 要减少几(小于0)
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }


    // ================================Map=================================

    /**
     * HashGet
     * @param key  键 不能为null
     * @param item 项 不能为null
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * HashSet 并设置时间
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }


    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }


    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }


    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     * @param key 键
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 获取set缓存的长度
     *
     * @param key 键
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */

    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将list放入缓存
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */

    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

}

5.2、测试使用redisUtil

package com.lemon;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lemon.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class Redis02SpringbootApplicationTests {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Test
    public void test1(){
        //向redis缓存中设置值
        redisUtil.set("name","zhangsna")
        System.out.println(redisUtil.get("name"));  
    }



    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("key", "呵呵");
        System.out.println(redisTemplate.opsForValue().get("key"));
    }

    @Test
    public void test() throws JsonProcessingException {
        User user = new User("皮卡丘",20);

        // 使用 JSON 序列化
        String s = new ObjectMapper().writeValueAsString(user);
        // 这里直接传入一个对象
        redisTemplate.opsForValue().set("user", s);
        System.out.println(redisTemplate.opsForValue().get("user"));
    }


}

6、补充

上面的练习的整个目录如下:

image.png

SpringBoot整合redis使用介绍(详细案例)

blog.csdn.net/weixin_4381…

www.cnblogs.com/yaoyaoling/…