springboot中操作redis实例分享

 更新时间:2023年06月19日 08:55:58   作者:minqiliang  
本文介绍了如何在Spring Boot应用中整合Redis缓存技术,包括配置Redis连接、定义Redis模板、实现Redis的基本操作以及使用Spring Cache注解。这些内容可帮助开发者快速掌握Spring Boot与Redis的集成,并提高应用性能。

1.maven引入相关依赖

<dependencies>
 	<!-- spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!--jackjson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>

2.配置redis

application.yml

spring:
  # 配置redis
  redis:
    host: 192.168.***.***
    port: 6379
    password: ******
    lettuce:
      pool:
        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
        max-idle: 8 # 连接池中的最大空闲连接
        max-wait: 100 # 连接池最大阻塞等待时间(使用负值表示没有限制)
        min-idle: 0 # 连接池中的最小空闲连接
    database: 0 # redis数据库索引(默认为0)

3.配置序列化

package com.example.config;

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis  序列化方式配置
 *
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 创建RedisTemplate<String, Object>对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
        // json方式序列化对象
        GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // value序列化方式采用jackson
        template.setValueSerializer(jsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jsonRedisSerializer);
        return template;
    }

}

4.测试类中进行测试

package com.example;

import com.example.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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 org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
class SpringDataRedisTestApplicationTests {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 测试redis的String类型
     */
    @Test
    void testString() {
        redisTemplate.opsForValue().set("name", "minqiliang");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }

    /**
     * 使用StringRedisTemplate操作redis(需要手动进行序列化和反序列化)
     * @throws JsonProcessingException
     */
    @Test
    void testString2() throws JsonProcessingException {
        // 创建一个对象
        User user = new User("001", "minqiliang", 18);
        // 由于StringRedisTemplate默认使用的是String的序列化器,所以这里需要将对象转换成json字符串
        String json = objectMapper.writeValueAsString(user);
        // 存入redis
        stringRedisTemplate.opsForValue().set("user:001", json);
        // 从redis中取出数据
        String s = stringRedisTemplate.opsForValue().get("user:001");
        // 将json字符串转换成对象
        User u = objectMapper.readValue(s, User.class);
        System.out.println(u);
    }

    @Test
    void testHash() {
        // 存入redis
        redisTemplate.opsForHash().put("user:002", "id", "002");
        redisTemplate.opsForHash().put("user:002", "name", "张三");
        redisTemplate.opsForHash().put("user:002", "age", 18);
        // 获取对应的key的所有值
        System.out.println(redisTemplate.opsForHash().entries("user:002"));
        System.out.println("====================================");
        // 获取对应的key的某个值
        System.out.println(redisTemplate.opsForHash().get("user:002", "id"));
        System.out.println(redisTemplate.opsForHash().get("user:002", "name"));
        System.out.println(redisTemplate.opsForHash().get("user:002", "age"));
    }
}

到此这篇关于springboot中操作redis实例分享的文章就介绍到这了,更多相关springboot中操作redis内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Redis 数据迁移的项目实践

    Redis 数据迁移的项目实践

    本文主要介绍了Redis 数据迁移的项目实践,通过Redis-shake的sync(同步)模式,可以将Redis的数据实时迁移至另一套Redis环境,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • 异步redis队列实现 数据入库的方法

    异步redis队列实现 数据入库的方法

    今天小编就为大家分享一篇异步redis队列实现 数据入库的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-10-10
  • Redis中的延迟双删

    Redis中的延迟双删

    这篇文章主要介绍了Redis中的延迟双删问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • Redis和Lua实现分布式限流器的方法详解

    Redis和Lua实现分布式限流器的方法详解

    这篇文章主要给大家介绍了关于Redis和Lua实现分布式限流器的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Redis和Lua具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-06-06
  • 一文搞懂阿里云服务器部署Redis并整合Spring Boot

    一文搞懂阿里云服务器部署Redis并整合Spring Boot

    这篇文章主要介绍了一文搞懂阿里云服务器部署Redis并整合Spring Boot,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • Redis分布式锁方案设计之防止订单重复提交或支付

    Redis分布式锁方案设计之防止订单重复提交或支付

    这篇文章主要为大家介绍了Redis分布式锁之防止订单重复提交或支付方案设计示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • 基于Redis实现分布式锁以及任务队列

    基于Redis实现分布式锁以及任务队列

    这篇文章主要介绍了基于Redis实现分布式锁以及任务队列,需要的朋友可以参考下
    2015-11-11
  • Redis如何解决BigKey

    Redis如何解决BigKey

    在Redis的使用过程中,我们经常会遇到BigKey, BigKey的大值会导致Redis内存中产生大量不连续的碎片,降低内存利用效率,本文主要介绍了Redis如何解决BigKey,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • RedisDesktopManager远程连接redis的实现

    RedisDesktopManager远程连接redis的实现

    本文主要介绍了RedisDesktopManager远程连接redis的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-05-05
  • 深入了解Redis的看门狗机制

    深入了解Redis的看门狗机制

    Redis锁的延期机制,通常被称为看门狗机制,本文就拉介绍一下Redis的看门狗机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12

最新评论