springboot项目启动,需要将msg_info这个表的 词条加载到redis,key+object的形式
时间: 2023-12-06 09:44:50 浏览: 68
spring boot 集成redis代码
可以使用Spring Boot的注解@PostConstruct在项目启动时加载msg_info表的词条到Redis中。具体实现步骤如下:
1. 添加Redis依赖,可以使用Spring Data Redis:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在RedisConfig类中配置RedisTemplate和StringRedisTemplate:
```java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(factory);
return stringRedisTemplate;
}
}
```
3. 在MsgInfoService类中注入RedisTemplate和MsgInfoMapper,实现加载msg_info表数据到Redis中的方法:
```java
@Service
public class MsgInfoService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private MsgInfoMapper msgInfoMapper;
@PostConstruct
public void init() {
List<MsgInfo> msgInfos = msgInfoMapper.findAll();
for (MsgInfo msgInfo : msgInfos) {
String key = "msg_info:" + msgInfo.getId();
redisTemplate.opsForValue().set(key, msgInfo);
}
}
//...
}
```
4. 在启动类上添加@EnableCaching注解开启缓存功能:
```java
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
这样在项目启动时就会自动加载msg_info表的词条到Redis中,以key+object的形式存储。
阅读全文