1、redis配置
依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redisconfig.java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
// 创建RedisTemplate对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 设置连接工厂
template.setConnectionFactory(connectionFactory);
// 创建JSON序列化工具
GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
// 设置Key的序列化
template.setKeySerializer(RedisSerializer.string());
template.setHashKeySerializer(RedisSerializer.string());
// 设置Value的序列化
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
// 返回
return template;
}
}
配置
#redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
2、实现
@Component
@Slf4j
public class InitConfig {
@Autowired
SysCityMapper cityMapper;
@Autowired
RedisTemplate<String, Object> redisTemplate;
//所有城市
private static List<PubListVo> allCity = new ArrayList<>();
private static List<SysCityDO> allCityList = new ArrayList<>();
/**
* 初始化省市县
*/
@PostConstruct
public void initProvinceCityRegion() {
//城市
allCityList = cityMapper.selectList(new LambdaQueryWrapper<>());
List<PubListVo> cityList = allCityList.stream().map(obj -> {
PubListVo vo = new PubListVo();
vo.setKey(obj.getCityCode().toString());
vo.setValue(obj.getName());
return vo;
}).collect(Collectors.toList());
allCity.addAll(cityList);
//放入redis
if (Boolean.TRUE.equals(redisTemplate.hasKey(CITY_KEY))) {
redisTemplate.delete(CITY_KEY);
}
List<SysCityDO> cityDOList = cityMapper.selectList(null);
Map<String, String> cityMap = cityDOList.stream()
.collect(Collectors.toMap(city -> String.valueOf(city.getCityCode()), SysCityDO::getName));
redisTemplate.opsForHash().putAll(CITY_KEY, cityMap);
}
/**
* 根据市名称查找市code
*/
public static Integer findCityKeyByName(String cityName) {
List<PubListVo> collect = allCity.stream()
.filter(obj -> obj.getValue().equalsIgnoreCase(cityName))
.collect(Collectors.toList());
if (collect.size() == 1) {
return Integer.parseInt(collect.get(0).getKey());
}
else
{
log.info("error:{}, collect:{}",cityName, collect.size());
}
return null;
}
/**
* 所有城市
*
* @return
*/
public static List<SysCityDO> getAllCityList() {
return allCityList;
}
}
初始化了两种:
一种是初始化数据放入list集合,获取InitConfig.getAllCityList()
,不能及时更新数据,必须重启项目。例如当系统添加一个城市后,数据库更新,但是代码层面没有重新获取新的数据。
另一种是放入了redis缓存中,通过redis获取,解决了第一种需要重启才能更新的弊端,可以在添加后redis添加对应的缓存。
标签:初始化,return,springboot,启动,redis,collect,template,new,public From: https://www.cnblogs.com/shirleyxueli/p/17452494.html