springboot项目启动,需要将msg_info这个表的 词条加载到redis,key+object的形式
时间: 2023-11-27 12:55:36 浏览: 79
spring boot 集成redis代码
可以使用Spring Boot的缓存注解来实现将msg_info表的数据加载到Redis里面。具体步骤如下:
1. 在pom.xml文件中引入Redis和Spring Boot缓存依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
```
2. 在Spring Boot的配置文件application.properties中配置Redis的连接信息:
```
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
```
3. 在Spring Boot项目中定义一个Redis缓存配置类,用于配置缓存的key和value的序列化方式:
```
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<>(Object.class)));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
}
}
```
4. 在需要缓存的方法上添加缓存注解,比如@Cacheable,示例代码如下:
```
@Service
public class MsgInfoService {
@Autowired
private MsgInfoMapper msgInfoMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Cacheable(value = "msgInfoCache", key = "#id")
public MsgInfo getById(Long id) {
return msgInfoMapper.getById(id);
}
@Cacheable(value = "msgInfoCache", key = "'all'")
public List<MsgInfo> getAll() {
return msgInfoMapper.getAll();
}
// 将数据加载到Redis中
public void loadMsgInfoToRedis() {
List<MsgInfo> msgInfos = msgInfoMapper.getAll();
for (MsgInfo msgInfo : msgInfos) {
redisTemplate.opsForValue().set("msg_info_" + msgInfo.getId(), msgInfo);
}
}
}
```
5. 在Spring Boot的启动类中调用loadMsgInfoToRedis方法,将数据加载到Redis中:
```
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// 加载msg_info表数据到Redis中
MsgInfoService msgInfoService = SpringContextHolder.getBean(MsgInfoService.class);
msgInfoService.loadMsgInfoToRedis();
}
}
```
这样就可以实现将msg_info表的数据加载到Redis里面了,key为"msg_info_id",value为MsgInfo对象序列化后的字符串。
阅读全文