SpringBoot2.0 整合CacheManager

1、引入相关的jar


     org.springframework.boot
      spring-boot-starter-data-redis

2、配置redis

spring:
  redis:
    password:
    host: 192.168.1.1

3、新增redis配置类

@EnableCaching
@Configuration
@AllArgsConstructor
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisTemplateConfig {
    private final RedisConnectionFactory factory;

    @Bean
    public RedisTemplate redisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }
}

4、使用CacheManger

注意:保存到cache里的实体,一定要序列化

@Autowired
    private CacheManager cacheManager;

@GetMapping("/cache")
    public Object getCache() {
        Cache cache = cacheManager.getCache("cache");
        if (cache != null && cache.get("user") != null) {
            return cache.get("user").get();
        }
        User user = new User(1,"zhangsan",20);
        cache.put("user", user);
        return user;

    }

 

 

 

你可能感兴趣的:(JAVA)