使用Spring Boot和Hazelcast实现分布式缓存
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public HazelcastInstance hazelcastInstance() {
return Hazelcast.newHazelcastInstance();
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
return new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance);
}
// 如果需要使用Redis作为分布式存储,取消注释以下配置
//
// @Bean
// public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
// .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
// return RedisCacheManager.builder()
// .cacheDefaults(cacheConfiguration)
// .transactionAware()
// .build();
// }
//
// @Bean
// public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// RedisTemplate<Object, Object> template = new RedisTemplate<>();
// template.setConnectionFactory(redisConnectionFactory);
// return template;
// }
}
这段代码配置了Spring Boot应用使用Hazelcast作为分布式缓存。HazelcastInstance
被创建并作为
评论已关闭