NutzCN Logo
精华 Nutz IOC 集成Ehcache3代码示例
发布于 2238天前 作者 lihongjie0209 1906 次浏览 复制 上一个帖子 下一个帖子
标签:

前置需求: 导入jar包


<!--ehcache 3 + jsr 107--> <!-- https://mvnrepository.com/artifact/org.ehcache/ehcache --> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> <version>1.0.0</version> </dependency>

首先拷贝官方的配置文件, 命名为 ehcache3.xml, 放在Maven项目的resources文件夹中

<!--

ehcache 3 的配置文件
由于项目版本的shiro session 缓存只支持ehcache2

为了保证项目的兼容性, ehcache2 只作为session缓存使用

除此之外, 所有缓存推荐使用ehcache3, 完全实现了JSR107, 扩展性和以及和其他项目的集成较好.


-->



<config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v3'
        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">

    <cache alias="foo">
        <key-type>java.lang.String</key-type>
        <value-type>java.lang.String</value-type>
        <resources>
            <heap unit="entries">2000</heap>
            <offheap unit="MB">500</offheap>
        </resources>
    </cache>

    <cache-template name="myDefaults">
        <key-type>java.lang.Long</key-type>
        <value-type>java.lang.String</value-type>
        <heap unit="entries">200</heap>
    </cache-template>

    <cache alias="bar" uses-template="myDefaults">
        <key-type>java.lang.Number</key-type>
    </cache>

    <cache alias="simpleCache" uses-template="myDefaults"/>

</config>

然后创建ioc文件ehcache3.js, 确保Nutz能扫描到就好:


var ioc = { eh3CacheManager: { type: "org.ehcache.core.EhcacheManager", args: [{refer: "xmlConfig"}], events: { create: "init", depose: 'close' } }, xmlConfig: { type: "org.ehcache.xml.XmlConfiguration", args: [{java: "org.nutz.lang.Files.findFile('ehcache3.xml').toURI().toURL()"}] } };

到这里基本就结束了, 为了调试方便, 我们在项目启动MainSetup中输出日志:

	private void initEh3(Ioc ioc) {
		org.ehcache.CacheManager eh3 = ioc.get(org.ehcache.CacheManager.class, "eh3CacheManager");

		Configuration configuration = eh3.getRuntimeConfiguration();

		Map<String, CacheConfiguration<?, ?>> configurationMap = configuration.getCacheConfigurations();


		for (Map.Entry<String, CacheConfiguration<?, ?>> entry : configurationMap.entrySet()) {


			logger.info(String.format("\n" +
							"Init cache %s\n" +
							"key type: %s\n" +
							"value type: %s\n",

					entry.getKey(),
					entry.getValue().getKeyType().getSimpleName(),
					entry.getValue().getValueType().getSimpleName()
			));


		}
	}

项目启动时应该输出日志如下:


[INFO ] 22:28:22.115 cn.boolin.mini.MainSetup.initEh3(MainSetup.java:105) - Init cache bar key type: Number value type: String [INFO ] 22:28:22.116 cn.boolin.mini.MainSetup.initEh3(MainSetup.java:105) - Init cache foo key type: String value type: String [INFO ] 22:28:22.116 cn.boolin.mini.MainSetup.initEh3(MainSetup.java:105) - Init cache simpleCache key type: Long value type: String
2 回复

很好很强大

添加回复
请先登陆
回到顶部