分布式ehcache缓存

今天在这里了记录一下学习ehcache分布式集群的过程。
ehcache的三种最为常用集群方式,分别是 RMI、JGroups 以及 EhCache Server 。
这里主要讲一下rmi方式。

1、添加依赖


net.sf.ehcache
ehcache
2.10.3

2、配置文件

spring.xml:



<context:component-scan base-package="com.yitop.feng" />


<cache:annotation-driven cache-manager="cacheManager" />





server1的ehcache.xml:









server2的ehcache.xml只要把提供者和监听者的端口调换就可以了

3、测试

这里是随便写个查询和写入缓存的方法

@CachePut(value = "cachetest", key = "#key")
public String put(String key, String value) {
System.out.println("保存数据, " + key + " : " + value);

return value;
}

@Cacheable(value = "cachetest", key = "#name")
public String getName(String name) {
return String.valueOf(System.currentTimeMillis());
}

下面是两个测试类,模拟两台服务器
test1

package com.yitop.feng;

import com.yitop.feng.service.EhcacheTestService;
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 java.util.Scanner;

/**
* @author fengzp
* @date 17/3/1下午2:19
* @email fengzp@gzyitop.com
* @company 广州易站通计算机科技有限公司
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class EhcacheTest {

@Autowired
private EhcacheTestService ehcacheTestService;

@Test
public void test() throws InterruptedException {
String name = "feng";

int i = 1;

while (true){
String o = ehcacheTestService.getName(name + i);
System.out.println(i + " : " + o);
i++;
Thread.sleep(1000);
if(i > 5) i = 1;
}
}
}

test2:

package com.yitop.feng;

import com.yitop.feng.service.EhcacheTestService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Scanner;

/**
* @author fengzp
* @date 17/3/1下午2:19
* @email fengzp@gzyitop.com
* @company 广州易站通计算机科技有限公司
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test2/spring2.xml"})
public class EhcacheTest2 {

@Autowired
private EhcacheTestService ehcacheTestService;

@Test
public void test() throws InterruptedException {

String name = "feng";

int i = 1;

while (true){
String o = ehcacheTestService.getName(name + i);
System.out.println(i + " : " + o);
i++;
if(i > 5){
i = 1;
break;
}
}

Thread.sleep(5000);

while (true) {
ehcacheTestService.put(name + i, i++ + "");
if(i > 5) break;
}

while (true){

}

}
}

4、结果

这里先启动test1,等它把数据都写到缓存后,启动test2。可以看到test2启动后能够读取到test1的缓存, 并且之后test2更新缓存后,test1也能同时更新,说明缓存已经成功集群到两边。

posted @ 2017-03-10 13:50  fengzp  阅读(7445)  评论(0)    收藏  举报