Spring Boot中RedisTemplate的使用

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

html 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<version>3.1.4</version>
</dependency>

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

bash 复制代码
spring
  redis:
    host: 127.0.0.1
    port: 6379

一、opsForHash

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

1.1 设置哈希字段的值

java 复制代码
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来进行序列化,因此我们要更改其序列化方式:

java 复制代码
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命令去查询刚刚存储的数据,这时又发现对应字段的值中文显示乱码:

bash 复制代码
\xe8\x8b\xb9\xe6\x9e\x9c

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

bash 复制代码
redis-cli --raw

1.2 设置多个哈希字段的值

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

java 复制代码
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 获取哈希字段的值

java 复制代码
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 获取多个哈希字段的值

java 复制代码
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 判断哈希中是否存在指定的字段

java 复制代码
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 获取哈希的所有字段

java 复制代码
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 获取哈希的所有字段的值

java 复制代码
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 获取哈希的所有字段和对应的值

java 复制代码
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。

java 复制代码
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 如果哈希的字段存在则不会添加,不存在则添加

java 复制代码
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 将指定字段的值增加指定步长

java 复制代码
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值的序列化方式要有所改变

java 复制代码
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(即字符串),使用语法上面完全一致。

java 复制代码
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());
    }
}
相关推荐
程序员岳焱24 分钟前
Java 与 MySQL 性能优化:Java 实现百万数据分批次插入的最佳实践
后端·mysql·性能优化
FrankYoou28 分钟前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
麦兜*1 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了1 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
大只鹅1 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
ai小鬼头1 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
天河归来1 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
weixin_478689762 小时前
十大排序算法汇总
java·算法·排序算法
码荼2 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud
IT_10242 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle