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来存储和操作数据了。

相关推荐
lay_liu13 小时前
ubuntu 安装 Redis
linux·redis·ubuntu
彭于晏Yan14 小时前
Spring AI(二):入门使用
java·spring boot·spring·ai
不是株16 小时前
Redis(入门篇)
数据库·redis·缓存
谁在黄金彼岸16 小时前
Spring Boot + WebFlux 全面使用指南
spring boot
希望永不加班17 小时前
SpringBoot 主启动类解释:@SpringBootApplication 到底做了什么
java·spring boot·后端·spring
智能工业品检测-奇妙智能17 小时前
国产化系统的性价比对比
人工智能·spring boot·后端·openclaw·奇妙智能
知识分享小能手19 小时前
Redis入门学习教程,从入门到精通, Redis Stack 完整语法知识点及使用指南(7)
数据库·redis·学习
SmartBrain19 小时前
Spring Boot的高性能技术栈的工程实践
spring boot·后端·架构
一个有温度的技术博主19 小时前
Redis系列八:Jedis连接池在java中的使用
java·redis·bootstrap
dreamxian19 小时前
苍穹外卖day09
java·spring boot·tomcat·log4j·maven