ip6*_*696 13 java spring ehcache spring-boot
我用Ehcache 2 + spring boot. 这是我的配置:
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
}
ehcache.xml - in resources.
Run Code Online (Sandbox Code Playgroud)
现在我想用Ehcache 3 + spring boot和Java的配置,而不是XML,但我还没有发现这方面的任何实例。我的问题:
1)为什么几乎所有的例子都是基于xml 的?这怎么能比java config更好呢?
2)如何在不使用xml的情况下在spring boot中使用java config配置Ehcache 3?
有很多例子。我个人是 Java 配置的粉丝。
以下是主要的官方示例:
这是用于创建 Ehcache 管理器 bean 的等效 java 配置。
应用程序配置文件
@Configuration
@EnableCaching
public class ApplicationConfig {
@Bean
public CacheManager ehCacheManager() {
CachingProvider provider = Caching.getCachingProvider();
CacheManager cacheManager = provider.getCacheManager();
CacheConfigurationBuilder<String, String> configuration =
CacheConfigurationBuilder.newCacheConfigurationBuilder(
String.class,
String.class,
ResourcePoolsBuilder
.newResourcePoolsBuilder().offheap(1, MemoryUnit.MB))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(20)));
javax.cache.configuration.Configuration<String, String> stringDoubleConfiguration =
Eh107Configuration.fromEhcacheCacheConfiguration(configuration);
cacheManager.createCache("users", stringDoubleConfiguration);
return cacheManager;
}
}
Run Code Online (Sandbox Code Playgroud)
服务实现程序
@Service
public class ServiceImpl {
@Cacheable(cacheNames = {"users"})
public String getThis(String id) {
System.out.println("Method called............");
return "Value "+ id;
}
}
Run Code Online (Sandbox Code Playgroud)
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7008 次 |
| 最近记录: |