SpringBoot整合Redis

SpringBoot整合redis

一、填加依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、编写RedisConfig配置类

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        // key采用String的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        // value序列化方式采用jackson
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

ServiceImpl中编写代码

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDAO cityDAO;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<City> findByCode(String CountryCode) {
        //设置redis的key键反序列化使其在redis数据库中变为可读
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        //根据key获取redis数据库中的值,如果有值就从缓存中取出,没有就查询数据库
        List<City> cities = (List<City>) redisTemplate.opsForValue().get("cities");
        //判断redis数据库中是否有该数据
        if (cities == null) {
            synchronized (this) {
                cities = (List<City>) redisTemplate.opsForValue().get("cities");
                if (cities == null) {
                    //没有该数据就查询数据库
                    cities = cityDAO.findByCode(CountryCode);
                    //将查询出来的数据添加到redis数据库中
                    redisTemplate.opsForValue().set("cities", cities);
                }
            }
        }
        return cities;
    }

正常使用controller调用该Service实现类,从而实现从redis中调用数据。

三、测试

@Test
  void contextLoads() {
   //填加string类型数据
   redisTemplate.opsForValue().set("youkey","youvalue");
   //填加hash类型数据
   redisTemplate.opsForHash().put("git","name","haluo");
   //创建对象,填加对象类型数据
   City city=new City();
   city.setID(1);
   city.setCountryCode("123");
   city.setDistrict("safas");
   city.setName("北京");
   city.setPopulation(123456789);
   //获取对象类型数据
   redisTemplate.opsForValue().set("user",city);
   //取出字符串对象
   System.out.println(redisTemplate.opsForValue().get("youkey"));
   //取出hash对象
  System.out.println(redisTemplate.opsForHash().get("git","name"));
  //取出实例对象
  List<City> cities = (List<City>)redisTemplate.opsForValue().get("cities");
   for (City city1 : cities) {
        System.out.println(city1);
     }
posted @ 2021-05-07 14:57  __先森  阅读(68)  评论(0编辑  收藏  举报