Spring Boot中RedisTemplate的使用示例详解

 更新时间:2023年10月24日 15:22:24   作者:y_bccl27  
RedisTemplate.opsForHash()是RedisTemplate类提供的用于操作Hash类型的方法,它可以用于对Redis中的Hash数据结构进行各种操作,如设置字段值、获取字段值、删除字段值等,本文介绍Spring Boot中RedisTemplate的使用,感兴趣的朋友一起看看吧

当前Spring Boot的版本为2.7.6,在使用RedisTemplate之前我们需要在pom.xml中引入下述依赖:

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

同时在application.yml文件中添加下述配置:

spring
  redis:
    host: 127.0.0.1
    port: 6379

一、opsForHash 

RedisTemplate.opsForHash()是RedisTemplate类提供的用于操作Hash类型的方法,它可以用于对Redis中的Hash数据结构进行各种操作,如设置字段值、获取字段值、删除字段值等。

1.1 设置哈希字段的值

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.RedisTemplate;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        redisTemplate.opsForHash().put("fruit:list", "1", "苹果");
    }
}

在上述代码能正常运行的情况下,我们在终端中执行 redis-cli 命令进入到redis的控制台中,然后执行 keys * 命令查看所有的key,结果发现存储在redis中的key不是设置的string值,前面还多出了许多类似 \xac\xed\x00\x05t\x00 这种字符串,如下图所示:

这是因为Spring-Data-Redis的RedisTemplate<K, V>模板类在操作redis时默认使用JdkSerializationRedisSerializer来进行序列化,因此我们要更改其序列化方式:

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;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
@Configuration
public class RedisTemplateConfig {
 
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        RedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
        return redisTemplate;
    }
}

需要说明的是这种配置只是针对所有的数据都是String类型,如果是其它类型,则根据需求修改一下序列化方式。 

使用 flushdb 命令清除完所有的数据以后,再次执行上述测试案例,接着我们再次去查看所有的key,这个看到数据已经正常:

接着使用 hget fruit:list 1 命令去查询刚刚存储的数据,这时又发现对应字段的值中文显示乱码:

\xe8\x8b\xb9\xe6\x9e\x9c

这个时候需要我们在进入redis控制台前,添加 --raw 参数:

redis-cli --raw

1.2 设置多个哈希字段的值

设置多个哈希字段的值一种很简单的粗暴的方法是多次执行opsForHash().put()方法,另外一种更优雅的方式如下:

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.RedisTemplate;
 
import java.util.HashMap;
import java.util.Map;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        Map<String,String> map = new HashMap<>();
        map.put("1","苹果");
        map.put("2","橘子");
        map.put("3","香蕉");
        redisTemplate.opsForHash().putAll("fruit:list",map);
    }
}

1.3 获取哈希字段的值

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.RedisTemplate;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        String value = (String) redisTemplate.opsForHash().get("fruit:list","1");
        System.out.println(value);
    }
}

1.4 获取多个哈希字段的值

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.RedisTemplate;
 
import java.util.Arrays;
import java.util.List;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        List<String> values = redisTemplate.opsForHash().multiGet("fruit:list", Arrays.asList("1", "2","3"));
        System.out.println(values);
    }
}

1.5 判断哈希中是否存在指定的字段

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.RedisTemplate;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        Boolean hasKey = redisTemplate.opsForHash().hasKey("fruit:list", "1");
        System.out.println(hasKey);
    }
}

1.6 获取哈希的所有字段

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.RedisTemplate;
 
import java.util.Set;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        Set<String> keys = redisTemplate.opsForHash().keys("fruit:list");
        System.out.println(keys);
    }
}

1.7 获取哈希的所有字段的值

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.RedisTemplate;
 
import java.util.List;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        List<String> values = redisTemplate.opsForHash().values("fruit:list");
        System.out.println(values);
    }
}

1.8 获取哈希的所有字段和对应的值

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.RedisTemplate;
 
import java.util.Map;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        Map<String, String> entries = redisTemplate.opsForHash().entries("fruit:list");
        System.out.println(entries);
    }
}

1.9 删除指定的字段 

返回值返回的是删除成功的字段的数量,如果字段不存在的话,则返回的是0。 

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.RedisTemplate;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        Long deletedFields = redisTemplate.opsForHash().delete("fruit:list", "4");
        System.out.println(deletedFields);
    }
}

1.10 如果哈希的字段存在则不会添加,不存在则添加 

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.RedisTemplate;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        Boolean success =  redisTemplate.opsForHash().putIfAbsent("fruit:list","4","西瓜");
        System.out.println(success);
    }
}

1.11 将指定字段的值增加指定步长

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.RedisTemplate;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        Long incrementedValue = redisTemplate.opsForHash().increment("salary:list", "1", 5);
        System.out.println(incrementedValue);
    }
}

如果字段不存在,则将该字段的值设置为指定步长,并且返回该字段当前的值;如果字段存在,则在该字段原有值的基础上增加指定步长,返回该字段当前的最新值。 该方法只适用于字段值为int类型的数据,因此关于哈希数据结构的value值的序列化方式要有所改变

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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
@Configuration
public class RedisTemplateConfig {
 
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        RedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }
}

StringRedisTemplate的好处就是在RedisTemplate基础上封装了一层,指定了所有数据的序列化方式都是采用StringRedisSerializer(即字符串),使用语法上面完全一致。 

public class StringRedisTemplate extends RedisTemplate<String, String> {
    public StringRedisTemplate() {
        this.setKeySerializer(RedisSerializer.string());
        this.setValueSerializer(RedisSerializer.string());
        this.setHashKeySerializer(RedisSerializer.string());
        this.setHashValueSerializer(RedisSerializer.string());
    }
}

二、opsForValue

RedisTemplate.opsForValue()是RedisTemplate类提供的用于操作字符串值类型的方法。它可以用于对Redis中的字符串值进行各种操作,如设置值、获取值、删除值等。

2.1 设置一个键值对

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.RedisTemplate;
 
import java.util.concurrent.TimeUnit;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        String key = "fruit";
        String value = "apple";
        redisTemplate.opsForValue().set(key,value,30,TimeUnit.SECONDS);
    }
}

2.2 根据键获取对应的值 

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.RedisTemplate;
 
@SpringBootTest
public class DemoApplicationTests {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    void test(){
        String value = (String) redisTemplate.opsForValue().get("fruit");
        System.out.println(value);
    }
}

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

相关文章

  • Java使用dom4j实现对xml简单的增删改查操作示例

    Java使用dom4j实现对xml简单的增删改查操作示例

    这篇文章主要介绍了Java使用dom4j实现对xml简单的增删改查操作,结合实例形式详细分析了Java使用dom4j实现对xml简单的增删改查基本操作技巧与相关注意事项,需要的朋友可以参考下
    2020-05-05
  • 解决本机安装的JDK8,启动IDEA2019没反应的问题(开发工具)

    解决本机安装的JDK8,启动IDEA2019没反应的问题(开发工具)

    这篇文章主要介绍了解决本机安装的JDK8启动IDEA2019没反应的问题(开发工具),非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-10-10
  • 一文带你搞懂Java中i++ 和 ++i的区别

    一文带你搞懂Java中i++ 和 ++i的区别

    在Java中,i++和++i都用于递增变量i的值,但它们之间有一个细微的区别,i++是后缀递增操作符,++i是前缀递增操作符,在大多数情况下,这两种递增操作的结果都是一样的,但在某些特定的表达式和逻辑中,它们可能会产生不同的效果,本文将带大家搞清Java中i++ 和 ++i的区别
    2023-09-09
  • java String源码和String常量池的全面解析

    java String源码和String常量池的全面解析

    下面小编就为大家分享一篇java String源码和String常量池的全面解析,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • 线程阻塞唤醒工具 LockSupport使用详解

    线程阻塞唤醒工具 LockSupport使用详解

    这篇文章主要为大家介绍了线程阻塞唤醒工具LockSupport使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-01-01
  • idea创建SpringBoot项目及注解配置相关应用小结

    idea创建SpringBoot项目及注解配置相关应用小结

    Spring Boot是Spring社区发布的一个开源项目,旨在帮助开发者快速并且更简单的构建项目,Spring Boot框架,其功能非常简单,便是帮助我们实现自动配置,本文给大家介绍idea创建SpringBoot项目及注解配置相关应用,感兴趣的朋友跟随小编一起看看吧
    2023-11-11
  • JVM原理之完整的一次GC流程解读

    JVM原理之完整的一次GC流程解读

    这篇文章主要介绍了JVM原理之完整的一次GC流程解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • Java通俗易懂系列设计模式之观察者模式

    Java通俗易懂系列设计模式之观察者模式

    这篇文章主要介绍了Java通俗易懂系列设计模式之观察者模式,对设计模式感兴趣的同学,一定要看一下
    2021-04-04
  • Java基础之让你彻底搞懂代理模式

    Java基础之让你彻底搞懂代理模式

    这篇文章主要介绍了Java基础之让你彻底搞懂代理模式,文中有非常详细的代码示例,对正在学习java基础的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • 在IDEA中maven配置MyBatis的流程详解

    在IDEA中maven配置MyBatis的流程详解

    刚学完javaweb,对自己的Dao层代码很不满意的话,可得来学学MyBatis.学习MyBatis既可以改进JDBC的使用,实现Dao层也会变得很简便,下面我将介绍IDEA中maven配置MyBatis简单流程,需要的朋友可以参考下
    2021-06-06

最新评论