二)spring 集成 ehcache jgroups 集群
依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- org.springframework.cache.ehcache.EhCacheCacheManager -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
</dependency>
<!-- 缓存集群同步(jgroups) -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-jgroupsreplication</artifactId>
<version>1.7</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.6.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
项目结构
│ pom.xml
│
├─src
│ ├─main
│ │ ├─java
│ │ │ └─cn
│ │ │ └─zno
│ │ │ Person.java
│ │ │ PersonService.java
│ │ │ PersonServiceImpl.java
│ │ │
│ │ └─resources
│ │ applicationContext-Ehcache.xml
│ │ ehcache.xml
│ │
│ └─test
│ ├─java
│ │ └─ehcache
│ │ TestEhcache.java
│ │
│ └─resources
applicationContext-Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config />
<context:component-scan base-package="cn.zno" /> <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 -->
<cache:annotation-driven cache-manager="cacheManager" /> <!-- 声明cacheManager -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="cacheManagerFactory" /> <!-- cacheManager工厂类,指定ehcache.xml的位置 -->
<bean id="cacheManagerFactory"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml"
p:shared="true" scope="singleton" />
</beans>
ehcache.xml (详细解释请看jgroups)
<?xml version="1.0" encoding="UTF-8"?> <ehcache updateCheck="false" dynamicConfig="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <diskStore path="java.io.tmpdir" /> <!--
UDP(
mcast_addr:Multicast address to be used for discovery
mcast_port:Multicast port for discovery packets. Default is 7555
bind_port:Port for discovery packets
ip_ttl:The time-to-live (TTL) for multicast datagram packets. Default is 8
mcast_send_buf_size:Send buffer size of the multicast datagram socket. Default is 100'000 bytes
mcast_recv_buf_size:Receive buffer size of the multicast datagram socket. Default is 500'000 bytes
)
PING(
timeout:
num_initial_members:Minimum number of initial members to get a response from
)
MERGE2(
min_interval:Minimum time in ms between runs to discover other clusters
max_interval:Maximum time in ms between runs to discover other clusters
)
FD_SOCK( )
VERIFY_SUSPECT(
timeout:
)
pbcast.NAKACK(
retransmit_timeout:
)
UNICAST( )
pbcast.STABLE(
desired_avg_gossip:
)
FRAG( )
pbcast.GMS(
join_timeout:
print_local_addr:
)
-->
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory"
properties="channel=ehcache^connect=UDP(mcast_addr=231.12.21.132;mcast_port=45566;bind_port=33433;ip_ttl=32;
mcast_send_buf_size=150000;mcast_recv_buf_size=80000):
PING(timeout=2000;num_initial_members=6):
MERGE2(min_interval=5000;max_interval=10000):
FD_SOCK:VERIFY_SUSPECT(timeout=1500):
pbcast.NAKACK(retransmit_timeout=3000):
UNICAST:
pbcast.STABLE(desired_avg_gossip=20000):
FRAG:
pbcast.GMS(join_timeout=5000;print_local_addr=true)"
propertySeparator="^"
/> <!--
<defaultCache> 是名为"default" 的<cache>
maxElementsInMemory:内存中最大元素个数。如果开启 overflowToDisk 则超出部分转移到磁盘;如未开启则会按照 memoryStoreEvictionPolicy 回收。
eternal:是否永驻内存
overflowToDisk:超出后转到磁盘。文件名为<cache> 的name 加后缀.data 例如:default.data
diskPersistent:在虚拟机重启时是否进行磁盘存储
timeToIdleSeconds:两次访问该元素的最大时间间隔,超出后失效
timeToLiveSeconds:创建后生存时间
maxElementsOnDisk:磁盘中最大元素个数
diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔
memoryStoreEvictionPolicy:内存回收策略
-->
<defaultCache maxElementsInMemory="1000000"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="120"
timeToLiveSeconds="300"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<!-- 同步缓存 -->
<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory" />
</defaultCache> <cache name="personCache" maxElementsInMemory="1000000"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="120"
timeToLiveSeconds="300"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory" />
</cache> </ehcache>
bean 及 服务类:
package cn.zno; public class Person { private int age;
private Car car; public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Car getCar() {
return car;
} public void setCar(Car car) {
this.car = car;
} @Override
public String toString() {
return "Person [age=" + age + ", car=" + car + "]";
} } class Car {
private String brand; public String getBrand() {
return brand;
} public void setBrand(String brand) {
this.brand = brand;
} @Override
public String toString() {
return "Car [brand=" + brand + "]";
}
}
PersonService.java
package cn.zno; public interface PersonService { public Person getPerson(); public void cleanPersonCache();
}
PersonServiceImpl.java
package cn.zno; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; @Service
public class PersonServiceImpl implements PersonService { @Cacheable(value = "personCache", key = "123456")
public Person getPerson(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Person person = new Person();
Car car = new Car();
car.setBrand("benz");
person.setAge(11);
person.setCar(car);
return person;
} @CacheEvict(value = "personCache", key = "123456")
public void cleanPersonCache() {
System.out.println("clean personCache[123456]");
} }
测试类:
package ehcache; import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.zno.PersonService; @ContextConfiguration(locations = { "classpath:applicationContext-Ehcache.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class TestEhcache { @Autowired
private CacheManager cacheManager;
@Autowired
private PersonService personService; @Test
public void show() {
// 未缓存时耗时
long t1 = System.currentTimeMillis();
System.out.println(personService.getPerson().toString());
long t2 = System.currentTimeMillis();
System.out.println("耗时:" + (t2 - t1));
// 缓存后耗时
long t3 = System.currentTimeMillis();
System.out.println(personService.getPerson().toString());
long t4 = System.currentTimeMillis();
System.out.println("耗时:" + (t4 - t3));
// 清除缓存后耗时
long t5 = System.currentTimeMillis();
personService.cleanPersonCache();
System.out.println(personService.getPerson().toString());
long t6 = System.currentTimeMillis();
System.out.println("耗时:" + (t6 - t5));
// 再次获取
long t7 = System.currentTimeMillis();
System.out.println(personService.getPerson().toString());
long t8 = System.currentTimeMillis();
System.out.println("耗时:" + (t8 - t7));
} @Test
public void create(){
cacheManager.addCache("testCache");
Cache cache = cacheManager.getCache("testCache");
cache.put(new Element("name", "xiaoming"));
System.out.println(cache.get("name"));
}
}
show()运行结果:
十月 07, 2015 11:03:22 上午 org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
信息: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
十月 07, 2015 11:03:22 上午 org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
信息: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
十月 07, 2015 11:03:22 上午 org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
信息: Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
十月 07, 2015 11:03:22 上午 org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
信息: Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/TransactionDefinition]
十月 07, 2015 11:03:22 上午 org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
信息: Using TestExecutionListeners: [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@15a191e, org.springframework.test.context.support.DirtiesContextTestExecutionListener@270664]
十月 07, 2015 11:03:22 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext-Ehcache.xml]
十月 07, 2015 11:03:22 上午 org.springframework.context.support.GenericApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@129df79: startup date [Wed Oct 07 11:03:22 CST 2015]; root of context hierarchy
十月 07, 2015 11:03:23 上午 org.springframework.cache.ehcache.EhCacheManagerFactoryBean afterPropertiesSet
信息: Initializing EhCache CacheManager
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. -------------------------------------------------------------------
GMS: address=pc012-, cluster=EH_CACHE, physical address=172.16.162.238:
-------------------------------------------------------------------
Person [age=, car=Car [brand=benz]]
耗时:
Person [age=, car=Car [brand=benz]]
耗时:
clean personCache[]
Person [age=, car=Car [brand=benz]]
耗时:
Person [age=, car=Car [brand=benz]]
耗时:
create()运行结果:
-------------------------------------------------------------------
GMS: address=pc012-40063, cluster=EH_CACHE, physical address=172.16.162.238:13550
-------------------------------------------------------------------
[ key = name, value=xiaoming, version=1, hitCount=1, CreationTime = 1444187930777, LastAccessTime = 1444187930777 ]
小结:
@Cacheable 的value是缓存名,key是在缓存中提取被缓存内容的key
<defaultCache 的作用是模板,不能通过default取出该缓存
<cache 可以配置到ehcache.xml 配置文件中,也可以在代码中手动添加(以<defaultCache 为模板)
mcast_addr 是组播地址,详细请查看jgroups
项目地址:git@github.com:witaste/ehcache.git
二)spring 集成 ehcache jgroups 集群的更多相关文章
- Spring Boot 2.x基础教程:使用EhCache缓存集群
上一篇我们介绍了在Spring Boot中整合EhCache的方法.既然用了ehcache,我们自然要说说它的一些高级功能,不然我们用默认的ConcurrentHashMap就好了.本篇不具体介绍Eh ...
- CAS (11) —— CAS TicketRegistry使用Ehcache的集群方案
CAS (11) -- CAS TicketRegistry使用Ehcache的集群方案 摘要 CAS TicketRegistry使用Ehcache的集群方案 版本 tomcat版本: tomcat ...
- Spring Cloud Alibaba | Nacos集群部署
目录 Spring Cloud Alibaba | Nacos集群部署 1. Nacos支持三种部署模式 2. 集群模式下部署Nacos 2.1 架构图 2.2 下载源码或者安装包 2.3 配置集群配 ...
- hadoop(二)搭建伪分布式集群
前言 前面只是大概介绍了一下Hadoop,现在就开始搭建集群了.我们下尝试一下搭建一个最简单的集群.之后为什么要这样搭建会慢慢的分享,先要看一下效果吧! 一.Hadoop的三种运行模式(启动模式) 1 ...
- Spring Boot MyBatis 数据库集群访问实现
Spring Boot MyBatis 数据库集群访问实现 本示例主要介绍了Spring Boot程序方式实现数据库集群访问,读库轮询方式实现负载均衡.阅读本示例前,建议你有AOP编程基础.mybat ...
- Spring Boot集成Hazelcast实现集群与分布式内存缓存
Hazelcast是Hazelcast公司开源的一款分布式内存数据库产品,提供弹性可扩展.高性能的分布式内存计算.并通过提供诸如Map,Queue,ExecutorService,Lock和JCach ...
- Quartz集成springMVC 的方案二(持久化任务、集群和分布式)
Quartz是一个开放源码项目,专注于任务调度器,提供了极为广泛的特性如持久化任务,集群和分布式任务等. Quartz核心是调度器,还采用多线程管理. 1.持久化任务:当应用程序停止运行时,所有调度信 ...
- spring和Quartz的集群(二)
一:前沿 写完了这两篇才突然想起来,忘记了最关键的东西,那就是在配置文件这里的配置,还有数据库的配置.这是郁闷啊!继续吧! 二:内容配置 我们在集成的时候需要自己配置一个quartz.properti ...
- Spring + Jedis集成Redis(集群redis数据库)
前段时间说过单例redis数据库的方法,但是生成环境一般不会使用,基本上都是集群redis数据库,所以这里说说集群redis的代码. 1.pom.xml引入jar <!--Redis--> ...
随机推荐
- xslt基础学习
今天下午工作完成没事,登w3c的网站学习了一下xslt的基础知识,主要是因为工作中xml用的比较多,xslt也有用到,所以在这里学习一下. XSLT:一种用于转换 XML 文档的语言. XSLT 用于 ...
- Apache Hive 存储方式、压缩格式
简介: Apache hive 存储方式跟压缩格式! 1.Text File hive> create external table tab_textfile ( host string com ...
- Implementing On Item Click / Double Click for TListView
ListView.On Item Click & ListView.On Item Double Click To be able to locate the clicked (if ther ...
- .Spark Streaming(上)--实时流计算Spark Streaming原理介
Spark入门实战系列--7.Spark Streaming(上)--实时流计算Spark Streaming原理介绍 http://www.cnblogs.com/shishanyuan/p/474 ...
- java多线程实例
import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurr ...
- express + mongodb 搭建一个简易网站 (三)
express + mongodb 搭建一个简易网站 (三) 前面已经实现了基本的网站功能,现在我们就开始开搞一个完整的网站,现在整个网站的UI就是下面的这个样子. 我们网站的样子就照着这个来吧. 1 ...
- 给vim编辑器自动添加行号
1.只改变当前用户的vim 在~目录下 vim .vimrc添加一行 set number 即可(普通用户权限即可) 2. 改变所有用户的vim 打开文件 /etc/vimrc 添加一行 set n ...
- form 表单排序
<html> <head></head> <body> <form class="form-inline"> ...
- The partial charge density (1)
============================================================================================= The pa ...
- eclipse搭建struts2环境及所遇到的问题
最近几天一直在搭建struts2框架,本身struts2框架的搭建是非常简单的,但不知道为什么最近就是总是报错,报了一大串的错 首先就是每次在类的根路径下创建struts.xml时,就报错,也不知道为 ...