J2Cache最初的版本是在源码中写死的读取配置文件路径,这个在使用上就非常不灵活,无论是用配置中心管理还是其他都不好用,而2.X之后的版本增加了一项功能:动态构建J2Cache实例
J2CacheConfig config = new J2CacheConfig(); //填充 config 变量所需的配置信息 J2CacheBuilder builder = J2CacheBuilder.init(config); CacheChannel channel = builder.getChannel(); //进行缓存的操作 channel.close();
我的项目中一级缓存用了ehcache,二级缓存用redis,配置如下:
J2CacheConfig config = new J2CacheConfig();
config.setBroadcast("redis");
config.setL1CacheName("ehcache");
config.setL2CacheName("redis");
config.setSerialization("fst");
//基本配置
Properties redisProperties = new Properties();
redisProperties.setProperty("channel", "life_j2cache");
redisProperties.setProperty("hosts", "127.0.0.1:6379");
redisProperties.setProperty("timeout", "10000");
redisProperties.setProperty("password", "123456");
redisProperties.setProperty("database", "1");
redisProperties.setProperty("maxTotal", "100");
redisProperties.setProperty("maxIdle", "10");
redisProperties.setProperty("maxWaitMillis", "5000");
redisProperties.setProperty("minEvictableIdleTimeMillis", "60000");
redisProperties.setProperty("minIdle", "1");
redisProperties.setProperty("numTestsPerEvictionRun", "10");
redisProperties.setProperty("lifo", "false");
redisProperties.setProperty("softMinEvictableIdleTimeMillis", "10");
redisProperties.setProperty("testOnBorrow", "true");
redisProperties.setProperty("testOnReturn", "false");
redisProperties.setProperty("testWhileIdle", "true");
redisProperties.setProperty("timeBetweenEvictionRunsMillis", "300000");
redisProperties.setProperty("blockWhenExhausted", "false");
redisProperties.setProperty("jmxEnabled", "false");
redisProperties.setProperty("usePool", "true");
config.setBroadcastProperties(redisProperties);
/**
* 一级缓存配置
* */
Properties l1CacheProperties = new Properties();
l1CacheProperties.setProperty("name", "self_name_j2cache");
l1CacheProperties.setProperty("configXml", "/ehcache.xml");
config.setL1CacheProperties(l1CacheProperties);
/**
* 二级缓存配置(基础缓存配置和二级缓存配置有许多参数是通用的,所有我使用了同一个对象去设置参数)
* */
redisProperties.setProperty("mode", "single");
redisProperties.setProperty("storage", "hash");
redisProperties.setProperty("cluster_name", "self_cluster_name");
redisProperties.setProperty("namespace", "abcdefg");
redisProperties.setProperty("channel_name", "self_channel");
config.setL2CacheProperties(redisProperties);
//填充 config 变量所需的配置信息
J2CacheBuilder builder = J2CacheBuilder.init(config);
CacheChannel cache = builder.getChannel();
上面配置中的参数可以用spring注入的参数来代替,这样就可以通过配置中心来管理j2cache的配置文件了。