springboot项目启动,需要将msg_info这个表的 词条加载到redis,key+object的形式
时间: 2023-11-27 12:55:23 浏览: 34
可以使用Spring Boot提供的注解来实现将msg_info表的词条加载到Redis中。具体步骤如下:
1. 在pom.xml文件中引入Redis依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在Spring Boot配置文件中配置Redis连接信息:
```
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
```
3. 定义RedisTemplate,用于操作Redis:
```java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
```
4. 定义一个Service,用于从数据库中查询msg_info表的词条,并将其缓存到Redis中:
```java
@Service
public class MsgInfoService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private MsgInfoMapper msgInfoMapper;
public void loadMsgInfoToRedis() {
List<MsgInfo> msgInfoList = msgInfoMapper.selectAll();
for (MsgInfo msgInfo : msgInfoList) {
String key = "msg_info:" + msgInfo.getId();
redisTemplate.opsForValue().set(key, msgInfo);
}
}
}
```
5. 在Spring Boot启动类中调用loadMsgInfoToRedis方法:
```java
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private MsgInfoService msgInfoService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
msgInfoService.loadMsgInfoToRedis();
}
}
```
这样,在Spring Boot启动时会自动将msg_info表的词条加载到Redis中,并以key+object的形式存储。可以使用redisTemplate操作Redis获取缓存的数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)