Spring Boot中的操作怎么使用Redis实现

发布时间:2023-04-20 10:48:54 作者:iii
来源:亿速云 阅读:63

这篇文章主要讲解了“Spring Boot中的操作怎么使用Redis实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Boot中的操作怎么使用Redis实现”吧!

1.依赖

maven依赖如下,需要说明的是,spring-boot-starter-data-redis里默认是使用lettuce作为redis客户端的驱动,但是lettuce其实用的比较少,我们常用的还是jedis作为客户端的驱动,所以这里排除掉lettuce,引入jedis:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

2.依赖关系

spring data redis中依赖的关系:

Spring Boot中的操作怎么使用Redis实现

这个依赖关系想表达的是,Spring 是通过 RedisConnection操作Redis的,RedisConnection 则对原生的 Jedis 行封装。要获取RedisConnection接口对象是通过RedisConnectionFactory 生成的 。

3.配置

配置文件进行配置:

# Redis 连接配置

# Redis 连接配置
# 单机 Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
# 连接池配置
spring.redis.jedis.pool.max-idle=30
spring.redis.jedis.pool.max-total=50
spring.redis.jedis.pool.max-wait=2000ms

代码进行配置:

@Configuration
public class RedisConfig {
    private RedisConnectionFactory connectionFactory = null;
    @Bean
    public RedisConnectionFactory initRedisConnectionFactory(){
        if(connectionFactory!=null){
            return connectionFactory;
        }
        JedisPoolConfig poolConfig =new JedisPoolConfig();
        //最大空闲数
        poolConfig.setMaxIdle(30);
        //最大连接数
        poolConfig.setMaxTotal(50);
        //最大等待毫秒数
        poolConfig.setMaxWaitMillis(2000);
        //创建Jedis连接工厂
        JedisConnectionFactory connectionFactory=new JedisConnectionFactory(poolConfig);
        //获取单机的redis配置,如果是集群的话用集群配置类
        RedisStandaloneConfiguration rscfg=connectionFactory.getStandaloneConfiguration();
        connectionFactory.setHostName("127.0.0.1");
        connectionFactory.setPort(6379);
        return connectionFactory;
    }
}

4.RedisTemplate

这里要说明的是如果是直接使用RedisConnection来操作redis就需要我们手动去找RedisConnectionFactory拿RedisConnection,并且需要每次手动关闭RedisConnection。所以Spring Data Redis里面提供了RedisTemplate来方便操作,其封装自jedis,屏蔽了资源获取和释放的步骤。

使用RedisTemplate的时候要注意的核心是它的序列化器,RedisTemplate有多种序列化器,不同的序列化器在键值写入、读出redis的过程中使用的序列化方式会不同,序列化出来的结果也会不同。比如处理字符就需要用字符串专用的序列化器、处理对象需要使用对象专用的序列化器。

目前有的序列化器如下:

Spring Boot中的操作怎么使用Redis实现

StringRedisSerializer:

StringRedisSerializer 是 RedisTemplate 默认使用的 Key 和 Value 的序列化器,它将字符串序列化为字节数组,使用 UTF-8 编码。由于 Redis 中 Key 和 Value 都是字符串,因此默认的 StringRedisSerializer 序列化器已经可以满足大部分情况的需要。

Jackson2JsonRedisSerializer:

Jackson2JsonRedisSerializer 是一个基于 Jackson 的 Redis Key 和 Value 的序列化器,它可以将对象序列化为 JSON 格式的字符串,并存储到 Redis 中。使用 Jackson2JsonRedisSerializer 序列化器需要添加 Jackson 的依赖,可以将对象转换为 JSON 格式的字符串,也可以将 JSON 格式的字符串转换为对象。

JdkSerializationRedisSerializer:

JdkSerializationRedisSerializer 是一种基于 Java 自带的序列化方式的序列化器,它可以将对象序列化为字节数组进行存储。虽然 JdkSerializationRedisSerializer 简单易用,但是它的效率比较低,序列化后的字节数组也比较大,不适合存储大量的数据。

GenericJackson2JsonRedisSerializer:

GenericJackson2JsonRedisSerializer 是一个支持泛型的 Jackson2JsonRedisSerializer,它可以序列化任意类型的对象,并将对象序列化为 JSON 格式的字符串。它在序列化和反序列化时都需要指定目标类型。

OxmSerializer:

OxmSerializer 是一种基于 Spring 的 O/X 映射框架的序列化器,它支持将对象序列化为 XML 格式的字符串。虽然 OxmSerializer 灵活性较高,但是序列化和反序列化的性能比较低,不适合存储大量的数据。

总之,在选择序列化器时需要根据实际情况进行选择,根据数据类型和性能要求选择合适的序列化器。

使用的时候直接set进去即可,set的时候给了很多生效粒度选择,是对所有redis类型的数据结构都生效,还是对某一类redis的数据结构类型生效:

Spring Boot中的操作怎么使用Redis实现

比如我想使用String序列化器,在全局都生效:

@Bean
public RedisTemplate<Object,Object> initRedisTemplate(){
  RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
  redisTemplate.setDefaultSerializer(new StringRedisSerializer());
  return redisTemplate;
}

5.基础操作

以下是使用RedisTemplate操作redis基本数据类型的代码示例:

要注意的是@Bean定义RedisTemplate的时候泛型要和使用时的泛型对齐。

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public void setString(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }
    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
    public void setHash(String key, String hashKey, Object value) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.put(key, hashKey, value);
    }
    public Object getHash(String key, String hashKey) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        return hashOps.get(key, hashKey);
    }
    public void setList(String key, Object value) {
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        listOps.rightPush(key, value);
    }
    public Object getList(String key, long index) {
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        return listOps.index(key, index);
    }
    public void setSet(String key, Object value) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        setOps.add(key, value);
    }
    public Object getSet(String key) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        return setOps.members(key);
    }
    public void setZSet(String key, Object value, double score) {
        ZSetOperations<String, Object> zsetOps = redisTemplate.opsForZSet();
        zsetOps.add(key, value, score);
    }
    public Object getZSet(String key, long start, long end) {
        ZSetOperations<String, Object> zsetOps = redisTemplate.opsForZSet();
        return zsetOps.range(key, start, end);
    }
}

6.事务

以下是使用事务的代码示例:

@Autowired
private RedisTemplate<String, String> redisTemplate;
public void transactionalOperation() {
    // 开启 Redis 事务
    redisTemplate.multi();
    try {
        // 执行多个 Redis 命令
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");
        // 提交事务
        redisTemplate.exec();
    } catch (Exception e) {
        // 回滚事务
        redisTemplate.discard();
    }
}

感谢各位的阅读,以上就是“Spring Boot中的操作怎么使用Redis实现”的内容了,经过本文的学习后,相信大家对Spring Boot中的操作怎么使用Redis实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. Spring Boot的Docker打包插件有哪些区别
  2. Spring Boot统一异常处理能拦截所有的异常吗

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot redis

上一篇:php如何把数组分割到6个

下一篇:PHP怎么将带有汉字的JSON格式转换为数组

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》