广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot中操作使用Redis实现详解
  • 106
分享到

SpringBoot中操作使用Redis实现详解

SpringBootRedisSpringBoot整合Redis 2023-05-16 20:05:11 106人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录1.依赖2.依赖关系3.配置4.RedisTemplate5.基础操作6.事务1.依赖 Maven依赖如下,需要说明的是,spring-boot-starter-data-red

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 是通过 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的过程中使用的序列化方式会不同,序列化出来的结果也会不同。比如处理字符就需要用字符串专用的序列化器、处理对象需要使用对象专用的序列化器。

目前有的序列化器如下:

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的数据结构类型生效:

比如我想使用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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot中操作使用Redis实现详解

本文链接: https://www.lsjlt.com/news/210506.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作