配置redis作为缓存容器:
@Configuration
public class RedisConfig {
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
return RedisCacheConfiguration
.defaultCacheConfig()
.computePrefixWith(name -> Const.CACHE_KEY_PREFIX + name + ":")
.serializeKeysWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
}
定义缓存接口
import com.cusc.onstar.hfc.compute.entity.ThresholdEntity;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.mongodb.repository.MongoRepository;
@CacheConfig(cacheNames = "thresholdEntity")
public interface ThresholdRepository extends MongoRepository<ThresholdEntity, String> {
@Cacheable(key = "#p0")
ThresholdEntity findByPackageCode(String packageCode);
@CachePut(key = "#p0.packageCode")
@Override
<S extends ThresholdEntity> S save(S s);
boolean existsByPackageCode(String packageCode);
}
程序入口开启缓存@EnableCaching
@EnableAsync
@EnableCaching
@SpringBootApplication
public class HfcComputeApplication {
public static void main(String[] args) {
SpringApplication.run(HfcComputeApplication.class, args);
}
}