依赖

        <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 集群的更多相关文章

  1. Spring Boot 2.x基础教程:使用EhCache缓存集群

    上一篇我们介绍了在Spring Boot中整合EhCache的方法.既然用了ehcache,我们自然要说说它的一些高级功能,不然我们用默认的ConcurrentHashMap就好了.本篇不具体介绍Eh ...

  2. CAS (11) —— CAS TicketRegistry使用Ehcache的集群方案

    CAS (11) -- CAS TicketRegistry使用Ehcache的集群方案 摘要 CAS TicketRegistry使用Ehcache的集群方案 版本 tomcat版本: tomcat ...

  3. Spring Cloud Alibaba | Nacos集群部署

    目录 Spring Cloud Alibaba | Nacos集群部署 1. Nacos支持三种部署模式 2. 集群模式下部署Nacos 2.1 架构图 2.2 下载源码或者安装包 2.3 配置集群配 ...

  4. hadoop(二)搭建伪分布式集群

    前言 前面只是大概介绍了一下Hadoop,现在就开始搭建集群了.我们下尝试一下搭建一个最简单的集群.之后为什么要这样搭建会慢慢的分享,先要看一下效果吧! 一.Hadoop的三种运行模式(启动模式) 1 ...

  5. Spring Boot MyBatis 数据库集群访问实现

    Spring Boot MyBatis 数据库集群访问实现 本示例主要介绍了Spring Boot程序方式实现数据库集群访问,读库轮询方式实现负载均衡.阅读本示例前,建议你有AOP编程基础.mybat ...

  6. Spring Boot集成Hazelcast实现集群与分布式内存缓存

    Hazelcast是Hazelcast公司开源的一款分布式内存数据库产品,提供弹性可扩展.高性能的分布式内存计算.并通过提供诸如Map,Queue,ExecutorService,Lock和JCach ...

  7. Quartz集成springMVC 的方案二(持久化任务、集群和分布式)

    Quartz是一个开放源码项目,专注于任务调度器,提供了极为广泛的特性如持久化任务,集群和分布式任务等. Quartz核心是调度器,还采用多线程管理. 1.持久化任务:当应用程序停止运行时,所有调度信 ...

  8. spring和Quartz的集群(二)

    一:前沿 写完了这两篇才突然想起来,忘记了最关键的东西,那就是在配置文件这里的配置,还有数据库的配置.这是郁闷啊!继续吧! 二:内容配置 我们在集成的时候需要自己配置一个quartz.properti ...

  9. Spring + Jedis集成Redis(集群redis数据库)

    前段时间说过单例redis数据库的方法,但是生成环境一般不会使用,基本上都是集群redis数据库,所以这里说说集群redis的代码. 1.pom.xml引入jar <!--Redis--> ...

随机推荐

  1. Spring Boot Unregistering JMX-exposed beans on shutdown

    创建springboot项目运行的时候报这个错误Unregistering JMX-exposed beans on shutdown,搜索发现第一条是: Spring boot 嵌入的tomcat不 ...

  2. ArcGIS案例学习笔记4_1

    ArcGIS案例学习笔记4_1 联系方式:谢老师,135-4855-4328, xiexiaokui(#)qq.com 时间:第四天上午 案例1:矢量校正案例 教程:Editing编辑教程 pdf 数 ...

  3. 大型运输行业实战_day02_2_数据模型建立

    1.模型分析 1.基本必备字段 id   state  type   createTime   updateTime 2.车票  :   车次   开始车站   到达车站   出发时间    票价   ...

  4. 警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Weixin' did not find a matching property.

    警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclips ...

  5. nyoj743-复杂度 【排列组合】

    http://acm.nyist.net/JudgeOnline/problem.php?pid=743 复杂度 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 fo ...

  6. Frog and Portal(思维好题)

    Frog and Portal https://hihocoder.com/problemset/problem/1873 时间限制:1000ms 单点时限:1000ms 内存限制:512MB 描述 ...

  7. P3157 [CQOI2011]动态逆序对

    P3157 [CQOI2011]动态逆序对 https://www.luogu.org/problemnew/show/P3157 题目描述 对于序列A,它的逆序对数定义为满足i<j,且Ai&g ...

  8. The valid characters are defined in RFC 7230 and RFC 3986

    网上大都说什么发送格式与协议定义的不兼容,改tomcat版本或改编码之类的. 本人测试的时候换了个浏览器,不用IE就好了 如果坚持用ie,也有解决方式 @参考文章 成功的方法 在请求地址var url ...

  9. OpenStack概念架构简述

    什么是OpenStack OpenStack既是一个社区,也是一个项目和一个开源软件,它提供了一个部署云的操作平台或工具集.其宗旨在于,帮助组织运行为虚拟计算或存储服务的云,为公有云.私有云,也为大云 ...

  10. nginx反向代理部署与演示(二)

    我们把LB01作为负载均衡器,WEB01和WEB02作为两台web服务器.   WEB01与WEB02虚拟主机配置如下:   我们修改nginx下的conf/nginx.conf文件,在http{}中 ...