Spring Boot中整合Redis

要在Spring Boot中整合Redis,你需要执行以下步骤:

  1. 添加依赖
    在你的pom.xml文件中添加以下依赖:
xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis
    application.propertiesapplication.yml文件中配置Redis连接信息:
properties 复制代码
# application.properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=your_password
spring.redis.database=0

或者

yaml 复制代码
# application.yml
spring:
  redis:
    host: localhost
    port: 6379
    password: your_password
    database: 0
  1. 使用RedisTemplate操作Redis
    在你的代码中,你可以使用RedisTemplate来操作Redis。首先,注入RedisTemplate
java 复制代码
@Autowired
private RedisTemplate<String, Object> redisTemplate;

然后,你可以使用redisTemplate的方法来操作Redis,例如:

java 复制代码
// 存储数据
redisTemplate.opsForValue().set("key", "value");

// 获取数据
Object value = redisTemplate.opsForValue().get("key");

// 删除数据
redisTemplate.delete("key");
  1. 自定义序列化方式(可选)
    默认情况下,Spring Boot使用JDK序列化方式。如果你想使用其他序列化方式,例如JSON,你可以配置RedisTemplate的序列化方式。例如,使用Jackson作为序列化方式:
java 复制代码
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(objectMapper);

        // 设置value的序列化规则和 key的序列化规则
        template.setValueSerializer(jacksonSeial);
        template.setKeySerializer(new StringRedisSerializer());

        template.afterPropertiesSet();
        return template;
    }
}

现在你已经成功整合了Spring Boot和Redis,可以开始使用Redis来存储和操作数据了。

相关推荐
篱笆院的狗4 分钟前
如何使用 Redis 快速实现布隆过滤器?
数据库·redis·缓存
howard20051 小时前
5.4.2 Spring Boot整合Redis
spring boot·整合redis
TracyCoder1231 小时前
接口限频算法:漏桶算法、令牌桶算法、滑动窗口算法
spring boot·spring·限流
小鸡脚来咯1 小时前
redis分片集群架构
数据库·redis·架构
什么都想学的阿超1 小时前
【Redis系列 03】掌握Redis编程艺术:事务、管道与Lua脚本完全指南
redis·junit·lua
饮长安千年月1 小时前
JavaSec-SpringBoot框架
java·spring boot·后端·计算机网络·安全·web安全·网络安全
考虑考虑2 小时前
Jpa中的@ManyToMany实现增删
spring boot·后端·spring
你不是我我3 小时前
【Java开发日记】说一说 SpringBoot 中 CommandLineRunner
java·开发语言·spring boot
yuan199973 小时前
Spring Boot 启动流程及配置类解析原理
java·spring boot·后端
楚歌again3 小时前
【如何在IntelliJ IDEA中新建Spring Boot项目(基于JDK 21 + Maven)】
java·spring boot·intellij-idea