好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring中RedisTemplate的基本使用浅析

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版本)

  引入依赖:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

< 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使用:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

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的序列化方式

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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对象,指定泛型类型

?

1

2

@Autowired

private RedisTemplate<String, String> redisTemplate;

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

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

?

1

2

3

redisTemplate.setValueSerializer(RedisSerializer.json());

// 针对于hash类型的value

redisTemplate.setHashValueSerializer(RedisSerializer.json());

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

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

原文链接:https://blog.csdn.net/gs2436/article/details/128743043

查看更多关于Spring中RedisTemplate的基本使用浅析的详细内容...

  阅读:14次