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

相关推荐
DemonAvenger2 分钟前
深入浅出 Redis 布隆过滤器:从原理到实战,10 年经验总结
数据库·redis·性能优化
Q_Q51100828510 小时前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
Q_Q51100828510 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
DokiDoki之父11 小时前
MyBatis—增删查改操作
java·spring boot·mybatis
摇滚侠13 小时前
Spring Boot 项目, idea 控制台日志设置彩色
java·spring boot·intellij-idea
爬山算法13 小时前
Redis(66)Redis如何实现分布式锁?
数据库·redis·分布式
恋红尘14 小时前
Redis面试八股
数据库·redis·面试
Code blocks15 小时前
GB28181视频服务wvp部署(一)
java·spring boot·后端
我命由我1234515 小时前
Spring Boot - Spring Boot 静态资源延迟响应(使用拦截器、使用过滤器、使用 ResourceResolver)
java·spring boot·后端·spring·java-ee·intellij-idea·intellij idea