Spring中RedisTemplate的基本使用浅析

Kefira ·
更新时间:2024-09-20
· 368 次阅读

目录

spring-data-redis项目

使用步骤

spring-data-redis项目

  spring-data-redis提供了在Spring应用中通过简单的配置访问redis服务,封装了 RedisTemplate 对象来对Redis进行各种操作、异常处理及序列化,支持发布订阅。RedisTemplate对应于Redis五大数据类型的api:

Api返回值类型说明
redisTemplate.opsForValue()ValueOperations操作 String 类型数据
redisTemplate.opsForHash()HashOperations操作 Hash 类型数据
redisTemplate.opsForList()ListOperations操作 List 类型数据
redisTemplate.opsForSet()SetOperations操作 Set 类型数据
redisTemplate.opsForZSet()ZSetOperations操作 SortedSet 类型数据
使用步骤

  前提条件:运行着的Redis(有windows版本)

  引入依赖:

<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.7.3</version> </dependency> <!--SpringBoot项目,可以引入这个依赖,这个依赖也是会依赖spring-data-redis的--> <!--<dependency>--> <!-- <groupId>org.springframework.boot</groupId>--> <!-- <artifactId>spring-boot-starter-data-redis</artifactId>--> <!-- <version>2.7.4</version>--> <!--</dependency>--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.7.4</version> </dependency>

  application.yml配置Redis的信息:

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    # 没有密码可以注释掉
    password: 123456
    database: 0
    lettuce:
      pool:
        # 最大连接
        max-active: 8
        # 最大空闲连接
        max-idle: 8
        # 最小空闲连接
        min-idle: 0
        # 连接等待时间
        max-wait: 100ms

  demo使用:

import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.DefaultTypedTuple; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @SpringBootTest public class RedisDemoApplicationTest { // 注入RedisTemplate @Autowired private RedisTemplate redisTemplate; // String类型 @Test void testString () { redisTemplate.opsForValue().set("name", "javaCoder"); Object name = redisTemplate.opsForValue().get("name"); System.out.println(name); } // Hash类型 @Test public void testHash () { redisTemplate.opsForHash().put("hash", "name", "abc"); redisTemplate.opsForHash().put("hash", "age", 18); Map map = redisTemplate.opsForHash().entries("hash"); System.out.println(map); } // List类型 @Test public void testList () { redisTemplate.opsForList().leftPushAll("list", "zhangsan", "li", "wanger"); List<String> names = redisTemplate.opsForList().range("list", 0, -1); System.out.println(names); } // Set类型 @Test public void testSet () { redisTemplate.opsForSet().add("set", "cat", "dog", "wolf", "pig", "sheep"); Set<String> set = redisTemplate.opsForSet().members("set"); System.out.println(set); } // SortedSet类型 @Test public void testSortedSet () { redisTemplate.opsForZSet().add("zset", "cat", 30); redisTemplate.opsForZSet().add("zset", "dog", 20); redisTemplate.opsForZSet().add("zset", "wolf", 80); redisTemplate.opsForZSet().add("zset", "pig", 40); Set<String> aClass = redisTemplate.opsForZSet().range("zset", 0, -1); System.out.println(aClass); //使用下面这套写法,也行 //Set<ZSetOperations.TypedTuple<String>> set = new HashSet<>(); //set.add(new DefaultTypedTuple<>("cat", 30.0)); //set.add(new DefaultTypedTuple<>("dog", 20.0)); //set.add(new DefaultTypedTuple<>("wolf", 80.0)); //set.add(new DefaultTypedTuple<>("pig", 40.0)); //redisTemplate.opsForZSet().add("zset", set); //Set<String> aClass1 = redisTemplate.opsForZSet().range("zset", //0, -1); //System.out.println(aClass1); } }

  此时代码运行起来没问题,但用redis-cli客户端,用相关命令去查看时,发现数据不存在(get name、hgetall hash、lrange list 0 -1、smembers set、zrange zset 0 -1),用如下解决方法:

  a.设置RedisTemplate对象的key的序列化方式

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate( RedisConnectionFactory connectionFactory) { // 创建 RedisTemplate 对象 RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); // 设置连接工厂 redisTemplate.setConnectionFactory(connectionFactory); // 设置Key的序列化 - String 序列化 RedisSerializer.string() => // StringRedisSerializer.UTF_8 redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); // 返回 return redisTemplate; } }

  b.注入的RestTemplate对象,指定泛型类型

@Autowired private RedisTemplate<String, String> redisTemplate;

  不过方法a又有问题啦,去看String类型的key:name的值,

  长长的一串,占用空间大,可读性差。这是因为value的序列化方式默认是JdkSerializationRedisSerializer,把它改成json。在上方的RedisConfig类中,添加代码:

redisTemplate.setValueSerializer(RedisSerializer.json()); // 针对于hash类型的value redisTemplate.setHashValueSerializer(RedisSerializer.json());

  如果你的redisTemplate类型确定就是RedisTemplate<String, String>,那也可以用StringRedisTemplate,两者效果一样。

到此这篇关于Spring中RedisTemplate的基本使用浅析的文章就介绍到这了,更多相关Spring RedisTemplate内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



spring

需要 登录 后方可回复, 如果你还没有账号请 注册新账号