jiangjin 5 anni fa
parent
commit
ff3ebcf42b
30 ha cambiato i file con 2621 aggiunte e 0 eliminazioni
  1. 27 0
      ipu-redis-example/.classpath
  2. 2 0
      ipu-redis-example/.gitignore
  3. 56 0
      ipu-redis-example/ipu-cache.iml
  4. 78 0
      ipu-redis-example/pom.xml
  5. 16 0
      ipu-redis-example/readme.txt
  6. 124 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/CacheFactory.java
  7. 42 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/ICache.java
  8. 163 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/config/IpuCacheConfig.java
  9. 66 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/jvm/JCache.java
  10. 38 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/mem/IMemCache.java
  11. 95 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/mem/impl/MemCache.java
  12. 111 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/mem/impl/WadeMemCache.java
  13. 140 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/IRedisCache.java
  14. 182 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/RedisCacheFactory.java
  15. 305 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/impl/JedisCache.java
  16. 300 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/impl/JedisClusterCache.java
  17. 15 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/listener/AbstractPubSubListener.java
  18. 33 0
      ipu-redis-example/src/main/java/com/ai/ipu/cache/util/IpuCacheConstant.java
  19. 67 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/CacheFactoryTest.java
  20. 46 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/config/IpuCacheConfigTest.java
  21. 24 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/mem/MemcacheTest.java
  22. 69 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/JedisCacheTest.java
  23. 41 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/PubSubListenerTest.java
  24. 85 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/RedisCacheTest.java
  25. 111 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/RedisClusterTest.java
  26. 225 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/RedisTest.java
  27. 53 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/context/IpuContextData.java
  28. 48 0
      ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/context/IpuContextData2.java
  29. 47 0
      ipu-redis-example/src/test/reources/ipu-cache.xml
  30. 12 0
      ipu-redis-example/src/test/reources/memcache.xml

+ 27 - 0
ipu-redis-example/.classpath

@ -0,0 +1,27 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
3
	<classpathentry kind="src" output="target/classes" path="src/main/java">
4
		<attributes>
5
			<attribute name="optional" value="true"/>
6
			<attribute name="maven.pomderived" value="true"/>
7
		</attributes>
8
	</classpathentry>
9
	<classpathentry kind="src" path="src/test/reources"/>
10
	<classpathentry kind="src" output="target/test-classes" path="src/test/java">
11
		<attributes>
12
			<attribute name="optional" value="true"/>
13
			<attribute name="maven.pomderived" value="true"/>
14
		</attributes>
15
	</classpathentry>
16
	<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
17
		<attributes>
18
			<attribute name="maven.pomderived" value="true"/>
19
		</attributes>
20
	</classpathentry>
21
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
22
		<attributes>
23
			<attribute name="maven.pomderived" value="true"/>
24
		</attributes>
25
	</classpathentry>
26
	<classpathentry kind="output" path="target/classes"/>
27
</classpath>

+ 2 - 0
ipu-redis-example/.gitignore

@ -0,0 +1,2 @@
1
/target/
2
/.settings/

+ 56 - 0
ipu-redis-example/ipu-cache.iml

@ -0,0 +1,56 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
3
  <component name="EclipseModuleManager">
4
    <conelement value="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER" />
5
    <src_description expected_position="0">
6
      <src_folder value="file://$MODULE_DIR$/src/main/java" expected_position="0" />
7
      <src_folder value="file://$MODULE_DIR$/src/test/reources" expected_position="1" />
8
      <src_folder value="file://$MODULE_DIR$/src/test/java" expected_position="2" />
9
    </src_description>
10
  </component>
11
  <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6">
12
    <output url="file://$MODULE_DIR$/target/classes" />
13
    <output-test url="file://$MODULE_DIR$/target/test-classes" />
14
    <content url="file://$MODULE_DIR$">
15
      <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
16
      <sourceFolder url="file://$MODULE_DIR$/src/test/reources" isTestSource="false" />
17
      <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
18
      <excludeFolder url="file://$MODULE_DIR$/target" />
19
    </content>
20
    <orderEntry type="sourceFolder" forTests="false" />
21
    <orderEntry type="library" name="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER" level="application" />
22
    <orderEntry type="inheritedJdk" />
23
    <orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" />
24
    <orderEntry type="library" name="Maven: log4j:log4j:1.2.8" level="project" />
25
    <orderEntry type="module" module-name="ipu-basic" />
26
    <orderEntry type="library" name="Maven: com.ai.ipu:ipu-common:3.1-SNAPSHOT" level="project" />
27
    <orderEntry type="library" name="Maven: com.mashape.unirest:unirest-java:1.3.8" level="project" />
28
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.3.2" level="project" />
29
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.3.1" level="project" />
30
    <orderEntry type="library" name="Maven: commons-logging:commons-logging:1.0.4" level="project" />
31
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpasyncclient:4.0.1" level="project" />
32
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore-nio:4.3.2" level="project" />
33
    <orderEntry type="library" name="Maven: org.apache.httpcomponents:httpmime:4.3.2" level="project" />
34
    <orderEntry type="library" name="Maven: org.json:json:20160810" level="project" />
35
    <orderEntry type="library" name="Maven: dom4j:dom4j:1.6.1" level="project" />
36
    <orderEntry type="library" name="Maven: xml-apis:xml-apis:1.0.b2" level="project" />
37
    <orderEntry type="library" name="Maven: jaxen:jaxen:1.1.1" level="project" />
38
    <orderEntry type="library" name="Maven: jdom:jdom:1.0" level="project" />
39
    <orderEntry type="library" name="Maven: xerces:xercesImpl:2.6.2" level="project" />
40
    <orderEntry type="library" name="Maven: xom:xom:1.0" level="project" />
41
    <orderEntry type="library" name="Maven: xerces:xmlParserAPIs:2.6.2" level="project" />
42
    <orderEntry type="library" name="Maven: xalan:xalan:2.6.0" level="project" />
43
    <orderEntry type="library" name="Maven: com.ibm.icu:icu4j:2.6.1" level="project" />
44
    <orderEntry type="library" name="Maven: org.jsoup:jsoup:1.7.2" level="project" />
45
    <orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.4" level="project" />
46
    <orderEntry type="library" name="Maven: org.apache.poi:poi:3.9" level="project" />
47
    <orderEntry type="library" name="Maven: commons-codec:commons-codec:1.3" level="project" />
48
    <orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.38" level="project" />
49
    <orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.23" level="project" />
50
    <orderEntry type="library" name="Maven: com.ai.wade:wade-data:1.0" level="project" />
51
    <orderEntry type="library" name="Maven: com.ai.wade:wade-cache:1.0" level="project" />
52
    <orderEntry type="library" name="Maven: com.ai.wade:wade-apache:1.0" level="project" />
53
    <orderEntry type="library" name="Maven: redis.clients:jedis:2.9.0" level="project" />
54
    <orderEntry type="library" name="Maven: org.apache.commons:commons-pool2:2.4.2" level="project" />
55
  </component>
56
</module>

+ 78 - 0
ipu-redis-example/pom.xml

@ -0,0 +1,78 @@
1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
	<modelVersion>4.0.0</modelVersion>
4
5
	<parent>
6
		<groupId>com.ai.ipu</groupId>
7
		<artifactId>ipu-aggregator</artifactId>
8
		<version>3.1-SNAPSHOT</version>
9
	</parent>
10
	
11
	<artifactId>ipu-cache</artifactId>
12
	<packaging>jar</packaging>
13
	<name>ipu-cache</name>
14
	<url>http://maven.apache.org</url>
15
16
	<properties>
17
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18
		<jedis>2.9.0</jedis>
19
	</properties>
20
21
	<dependencies>
22
		<!-- Central jar -->
23
		<dependency>
24
			<groupId>junit</groupId>
25
			<artifactId>junit</artifactId>
26
		</dependency>
27
		<dependency>
28
			<groupId>log4j</groupId>
29
			<artifactId>log4j</artifactId>
30
		</dependency>
31
		<dependency>
32
			<groupId>com.ai.ipu</groupId>
33
			<artifactId>ipu-basic</artifactId>
34
		</dependency>
35
		<dependency>
36
			<groupId>com.ai.ipu</groupId>
37
			<artifactId>ipu-common</artifactId>
38
		</dependency>
39
		<dependency>
40
			<groupId>com.ai.wade</groupId>
41
			<artifactId>wade-cache</artifactId>
42
		</dependency>
43
		<dependency>
44
			<groupId>com.ai.wade</groupId>
45
			<artifactId>wade-apache</artifactId>
46
		</dependency>
47
		<dependency>
48
		    <groupId>redis.clients</groupId>
49
		    <artifactId>jedis</artifactId>
50
		    <version>${jedis}</version>
51
		</dependency>
52
	</dependencies>
53
54
	<build>
55
		<plugins>
56
			<plugin>
57
				<groupId>org.apache.maven.plugins</groupId>
58
				<artifactId>maven-javadoc-plugin</artifactId>
59
				<version>2.9.1</version>
60
				<configuration>
61
62
					<nodeprecated>true</nodeprecated>
63
					<doclet>com.ai.ipu.javadoc.IpuDoclet</doclet>
64
					<useStandardDocletOptions>false</useStandardDocletOptions>
65
					<docletArtifact>
66
						<groupId>com.ai.ipu</groupId>
67
						<artifactId>ipu-javadoc</artifactId>
68
						<version>${ipu}</version>
69
					</docletArtifact>
70
					<encoding>UTF-8</encoding>
71
					<docencoding>UTF-8</docencoding>
72
					<charset>UTF-8</charset>
73
					<author>true</author>
74
				</configuration>
75
			</plugin>
76
		</plugins>
77
	</build>
78
</project>

+ 16 - 0
ipu-redis-example/readme.txt

@ -0,0 +1,16 @@
1
1. 配置文件命名原则:
2
第三方组件的自带配置文件,命名前缀加上ipu_,如:ipu-mybatis-config.xml。
3
4
2.redis环境和端口
5
121.42.183.206为测试环境;123.57.35.51地址是正式环境,不要作为测试服务。
6
redis服务的端口为10000-10999
7
(
8
kafka 9000-9999
9
mqtt 7000-7999
10
coap 5000-5999
11
rest 8000-8999
12
zookeeper 2000-2999
13
redis 10000-10999
14
ngnix 80
15
ftp 21
16
)

+ 124 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/CacheFactory.java

@ -0,0 +1,124 @@
1
package com.ai.ipu.cache;
2
3
import java.util.HashMap;
4
import java.util.Map;
5
6
import com.ai.ipu.basic.log.ILogger;
7
import com.ai.ipu.basic.log.IpuLoggerFactory;
8
import com.ai.ipu.cache.config.IpuCacheConfig;
9
import com.ai.ipu.cache.mem.impl.WadeMemCache;
10
import com.ai.ipu.cache.redis.RedisCacheFactory;
11
import com.ai.ipu.cache.redis.impl.JedisCache;
12
import com.ai.ipu.cache.redis.impl.JedisClusterCache;
13
import com.ai.ipu.cache.util.IpuCacheConstant;
14
import com.ailk.cache.memcache.MemCacheFactory;
15
16
/**
17
 * 缓存工厂方法
18
 */
19
public class CacheFactory {
20
    private static final ILogger LOGGER = IpuLoggerFactory.createLogger(CacheFactory.class);
21
    private static Map<String, ICache> caches = new HashMap<String, ICache>();
22
    public static final String DEFAULT_CACHE_NAME = "redis";
23
    
24
    private CacheFactory() {
25
    }
26
27
    public enum CacheType {
28
        mem, redis, jvm, wadeMem;
29
    }
30
31
    /**
32
     * 根据ipu-cache.xml或memcache.xml中的配置信息构造缓存实例
33
     * @param type 缓存的类型
34
     * @param cacheName 缓存的名称
35
     * @return 缓存的实例
36
     * @throws Exception
37
     */
38
    @SuppressWarnings("unused")
39
    public static ICache getCache(CacheType type, String cacheName) throws Exception {
40
        ICache cache = caches.get(cacheName);
41
42
        if (null == cache) { // 首次使用时加载缓存
43
            cache = getCache(cache, type, cacheName);
44
        }
45
        return cache;
46
    }
47
48
    /**
49
     * 根据ipu-cache.xml中的配置信息构造缓存实例,
50
     * @param cacheName 缓存的名称
51
     * @return 缓存的实例
52
     * @throws Exception
53
     */
54
    public static ICache getCache(String cacheName) throws Exception {
55
        String cacheType = IpuCacheConfig.getCacheType(cacheName);
56
        cacheType = cacheType == null ? DEFAULT_CACHE_NAME : cacheType;
57
        return getCache(CacheType.valueOf(cacheType), cacheName);
58
    }
59
    
60
    private static ICache createCache(CacheType type, String cacheName) throws Exception {
61
        /* 根据cacheName获取缓存类型 */
62
        switch (type) {
63
        case mem:
64
            break;
65
        case redis:
66
            if (IpuCacheConstant.ClientType.JEDIS_CLIENT.equalsIgnoreCase(IpuCacheConfig.getCacheDefaultAttr(cacheName,
67
                    IpuCacheConstant.Redis.CLIENT_TYPE, IpuCacheConstant.ClientType.JEDIS_CLIENT)))
68
                return new JedisCache(RedisCacheFactory.getJedis(cacheName));
69
            else
70
                return new JedisClusterCache(RedisCacheFactory.getJedisCluster(cacheName));
71
        case jvm:
72
            
73
            break;
74
        case wadeMem:
75
            return new WadeMemCache(MemCacheFactory.getCache(cacheName));
76
        default:
77
            break;
78
        }
79
        return null;
80
    }
81
    
82
    /**
83
     * 判断是否IPU缓存实例是否存在
84
     * @return {@code true} 存在; {@code false} 不存在
85
     */
86
    public static boolean isIpuCache(String cacheName) throws Exception {
87
        Map<String, Object> cacheEntity = IpuCacheConfig.getCacheEntity(cacheName);
88
        return cacheEntity != null && !cacheEntity.isEmpty();
89
    }
90
    
91
    /**
92
     * redis使用后,需要手工释放,进行资源回收
93
     * 集群不需要释放
94
     * 
95
     * @param cacheName
96
     * @param cache redis实例
97
     * @throws Exception
98
     */
99
    public static void close(String cacheName, ICache cache) throws Exception {
100
        if (cache == null)
101
            return;
102
        if (cache instanceof JedisCache)
103
            ((JedisCache)cache).close();
104
        else if (caches!=null && !caches.isEmpty())
105
            caches.remove(cacheName);
106
    }
107
    
108
    private static ICache getCache(ICache iCache, CacheType type, String cacheName) throws Exception {
109
        ICache cache = iCache;
110
        synchronized (CacheFactory.class) {
111
            if (cache!=null){ //避免时间差
112
                return cache;
113
            }
114
            cache = createCache(type, cacheName);
115
            if(!(type.equals(CacheType.redis)&&IpuCacheConstant.ClientType.JEDIS_CLIENT.equalsIgnoreCase(IpuCacheConfig.getCacheDefaultAttr(cacheName,
116
                    IpuCacheConstant.Redis.CLIENT_TYPE, IpuCacheConstant.ClientType.JEDIS_CLIENT))))
117
            {
118
                caches.put(cacheName, cache);
119
                LOGGER.info("初始化缓存"+cacheName+"成功");
120
            }
121
        }
122
        return cache;
123
    }
124
}

+ 42 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/ICache.java

@ -0,0 +1,42 @@
1
package com.ai.ipu.cache;
2
3
/**
4
 * cache接口定义
5
 */
6
public interface ICache {
7
    
8
    /**
9
     * 存
10
     * @return 是否存储成功
11
     */
12
    public boolean put(Object key, Object value) throws Exception;
13
14
    /**
15
     * 取
16
     * @return 存储的缓存的值
17
     */
18
    public Object get(Object key) throws Exception;
19
20
    /**
21
     * 移除
22
     * @return 是否移除成功
23
     */
24
    public boolean remove(Object key) throws Exception;
25
26
    /**
27
     * 清除
28
     */
29
    public void clear() throws Exception;
30
    
31
    /**
32
     * key是否存在
33
     * @return key是凑存在
34
     */
35
    public boolean keyExists(String cacheKey);
36
    
37
    /**
38
     * 存
39
     * @return 是否存储成功
40
     */
41
    public boolean put(Object key, Object value, int secondTimeout) throws Exception;
42
}

+ 163 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/config/IpuCacheConfig.java

@ -0,0 +1,163 @@
1
package com.ai.ipu.cache.config;
2
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.List;
6
import java.util.Map;
7
8
import com.ai.ipu.common.xml.Dom4jHelper;
9
10
/**
11
 * ipu-cache.xml配置文件解析
12
 *
13
 * @author huangbo@asiainfo.com
14
 */
15
public class IpuCacheConfig {
16
    private static final String CACHE_GONFIG_FILE = "ipu-cache.xml";
17
    private static final String ROOT_PATH = "caches";
18
    private static final String CONFIG_PATH = "cache";
19
    private static final String CONFIG_PATH_ARRT = CONFIG_PATH + Dom4jHelper.SUFFIX_ATTR;
20
    
21
    private static final String SERVERS_PATH = "servers";
22
    private static final String CONFIG_ATTR = "config_attr";
23
    private static final String SERVER_ATTR = "server_attr";
24
    
25
    private static final String CACHE_NAME = "cache_name";
26
    private static final String CACHE_TYPE = "cache_type";
27
    private static final String CACHE_SERVER = "cache_server";
28
    private static final String CACHE_ATTR = "cache_attr";
29
    /*属性*/
30
    private static final String ATTR_NAME = "name";
31
    private static final String ATTR_VALUE = "value";
32
    private static final String ATTR_TYPE = "type";
33
    
34
    private static IpuCacheConfig config;
35
    private Map<String, Object> cachesMap;
36
    
37
    @SuppressWarnings("unchecked")
38
    private IpuCacheConfig() throws Exception {
39
        Dom4jHelper dh = new Dom4jHelper(getClass().getClassLoader().getResourceAsStream(CACHE_GONFIG_FILE));
40
        Map<String, ?> originData = dh.getAll();
41
        List<Map<String, Object>> configs = (List<Map<String, Object>>) originData.get(ROOT_PATH);
42
        cachesMap = new HashMap<String, Object>();
43
        Map<String, Object> cacheMap;
44
        List<Map<String, String>> cacheServer;
45
        Map<String, String> configAttr;
46
        /*循环缓存实例*/
47
        for (Map<String, Object> config : configs) {
48
            cacheMap = new HashMap<String, Object>();
49
            cacheServer = new ArrayList<Map<String, String>>();
50
            configAttr = new HashMap<String, String>();
51
            
52
            Map<String, String> cacheAttrMap = (Map<String, String>) config.get(CONFIG_PATH_ARRT);
53
            List<Map<String, Object>> cacheList = (List<Map<String, Object>>)config.get(CONFIG_PATH);
54
            
55
            for(Map<String, Object> map : cacheList){
56
                if(map.get(CONFIG_ATTR)!=null){
57
                    /*解析缓存实例的属性*/
58
                    Map<String, String> configValue = (Map<String, String>)map.get(CONFIG_ATTR);
59
                    configAttr.put(configValue.get(ATTR_NAME), configValue.get(ATTR_VALUE));
60
                }else if(map.get(SERVERS_PATH)!=null){
61
                    /*解析缓存实例的服务列表*/
62
                    List<Map<String, Object>> serverList = (List<Map<String, Object>>)map.get(SERVERS_PATH);
63
                    for(Map<String, Object> server : serverList){
64
                        cacheServer.add((Map<String, String>)server.get(SERVER_ATTR));
65
                    }
66
                }
67
            }
68
            
69
            cacheMap.put(CACHE_NAME, cacheAttrMap.get(ATTR_NAME));
70
            cacheMap.put(CACHE_TYPE, cacheAttrMap.get(ATTR_TYPE));
71
            cacheMap.put(CACHE_ATTR, configAttr);
72
            cacheMap.put(CACHE_SERVER, cacheServer);
73
            cachesMap.put(cacheAttrMap.get(ATTR_NAME), cacheMap);
74
        }
75
    }
76
77
    /**
78
     * 获取实例
79
     * @return 返回的config实例
80
     * @throws Exception
81
     */
82
    protected static IpuCacheConfig getInstance() throws Exception {
83
        if (config == null) {
84
            config = new IpuCacheConfig();
85
        }
86
        return config;
87
    }
88
89
    /**
90
     * 获取cache map
91
     * @return 返回cache map 配置关系
92
     */
93
    public Map<String, Object> getCacheMap() {
94
        return cachesMap;
95
    }
96
97
    /**
98
     * 获取缓存的entity
99
     * @param cacheName
100
     * @return 返回缓存的entity
101
     * @throws Exception
102
     */
103
    @SuppressWarnings("unchecked")
104
    public static Map<String, Object> getCacheEntity(String cacheName) throws Exception {
105
        // TODO Auto-generated method stub
106
        return (Map<String, Object>)getInstance().getCacheMap().get(cacheName);
107
    }
108
109
    /**
110
     * 获取缓存的server
111
     * @param cacheName
112
     * @return 返回cache server
113
     * @throws Exception
114
     */
115
    @SuppressWarnings("unchecked")
116
    public static List<Map<String,String>> getCacheServers(String cacheName) throws Exception {
117
        // TODO Auto-generated method stub
118
        return (List<Map<String, String>>) getCacheEntity(cacheName).get(CACHE_SERVER);
119
    }
120
121
    /**
122
     * 获取缓存的属性
123
     * @param cacheName
124
     * @param name
125
     * @return 返回缓存的属性
126
     * @throws Exception
127
     */
128
    @SuppressWarnings("unchecked")
129
    public static String getCacheAttr(String cacheName, String name) throws Exception {
130
        // TODO Auto-generated method stub
131
        return ((Map<String, String>)getCacheEntity(cacheName).get(CACHE_ATTR)).get(name);
132
    }
133
134
    /**
135
     * 获取缓存的属性,不存在则使用默认值
136
     * @param cacheName
137
     * @param name
138
     * @param defaultValue
139
     * @return 缓存的属性
140
     * @throws Exception
141
     */
142
    public static String getCacheDefaultAttr(String cacheName, String name, String defaultValue) throws Exception {
143
        // TODO Auto-generated method stub
144
        String value = getCacheAttr(cacheName, name);
145
        return value == null ? defaultValue : value;
146
    }
147
148
    /**
149
     * 获取缓存类型
150
     * @param cacheName
151
     * @return 缓存的类型
152
     * @throws Exception
153
     */
154
    @SuppressWarnings("unchecked")
155
    public static String getCacheType(String cacheName) throws Exception {
156
        // TODO Auto-generated method stub
157
    	Object cache = getInstance().getCacheMap().get(cacheName);
158
    	if(cache==null){
159
    		return null;
160
    	}
161
        return (String)((Map<String, Object>)cache).get(CACHE_TYPE);
162
    }
163
}

+ 66 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/jvm/JCache.java

@ -0,0 +1,66 @@
1
package com.ai.ipu.cache.jvm;
2
3
import java.util.HashMap;
4
5
import com.ai.ipu.cache.ICache;
6
7
/**
8
 * JVM缓存
9
 */
10
public class JCache implements ICache{
11
    private HashMap cacheMap; //缓存
12
13
    public JCache(){
14
        cacheMap = new HashMap();
15
    }
16
    
17
    /**
18
     * 在jvm缓存中存放一个K-V键值对
19
     * @param key  key值
20
     * @param value value值
21
     * @return 
22
     * @exception Exception
23
     */
24
    public boolean put(Object key, Object value) throws Exception {    
25
        return cacheMap.put(key, value) != null;
26
    }
27
28
    /**
29
     * 在jvm缓存中得到key的value值
30
     * @param key  key值
31
     * @return Object value值
32
     * @exception Exception
33
     */
34
    public Object get(Object key) throws Exception {
35
        return cacheMap.get(key);
36
    }
37
38
    /**
39
     * 在jvm缓存中移除key
40
     * @param key  key值
41
     * @return boolean
42
     * @exception Exception
43
     */
44
    public boolean remove(Object key) throws Exception {
45
        Object value = cacheMap.remove(key);
46
        return value!=null;
47
    }
48
49
    /**
50
     * 清除jvm缓存所有值
51
     * @exception Exception
52
     */
53
    public void clear() throws Exception {
54
        cacheMap.clear();
55
    }
56
57
    @Override
58
    public boolean keyExists(String cacheKey) {
59
        return cacheMap.containsKey(cacheKey);
60
    }
61
62
    @Override
63
    public boolean put(Object key, Object value, int secondTimeout) throws Exception {
64
        return false;
65
    }
66
}

+ 38 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/mem/IMemCache.java

@ -0,0 +1,38 @@
1
package com.ai.ipu.cache.mem;
2
3
import com.ai.ipu.cache.ICache;
4
5
/**
6
 * MemCache接口
7
 */
8
public interface IMemCache extends ICache {
9
	/**
10
	 * 在缓存中存放一个K-V键值对,同名键会被覆盖。设置多少秒后超时
11
	 * @return 是否put成功
12
	 */
13
	public boolean put(Object key, Object value, int secondTimeout) throws Exception;
14
	
15
	/**
16
	 * 递增计数器(线程安全),步长为1。
17
     * @return 增加之后的值
18
	 */
19
	public long incr(String cacheKey);
20
	
21
	/**
22
	 * 递增计数器(线程安全),步长为inc。
23
     * @return 增加之后的值
24
	 */
25
	public long incr(String cacheKey, int inc);
26
	
27
	/**
28
	 * 递减计数器(线程安全), 步长为1。
29
     * @return 减少之后的值
30
	 */
31
	public long decr(String cacheKey);
32
	
33
	/**
34
	 * 递减计数器(线程安全), 步长为inc。
35
     * @return 减少之后的值
36
	 */
37
	public long decr(String cacheKey, int inc);
38
}

+ 95 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/mem/impl/MemCache.java

@ -0,0 +1,95 @@
1
package com.ai.ipu.cache.mem.impl;
2
3
import java.util.Map;
4
5
import com.ai.ipu.basic.doc.NonJavaDoc;
6
import com.ai.ipu.cache.mem.IMemCache;
7
8
/**
9
 * MemCache 实现
10
 */
11
@NonJavaDoc
12
public class MemCache implements IMemCache{
13
14
	/**
15
	 * 存
16
	 */
17
	public boolean put(Object key, Object value) throws Exception {
18
		// TODO Auto-generated method stub
19
		return false;
20
	}
21
22
	/**
23
	 * 取
24
	 */
25
	public Object get(Object key) throws Exception {
26
		// TODO Auto-generated method stub
27
		return null;
28
	}
29
30
	/**
31
	 * 移除
32
	 */
33
	public boolean remove(Object key) throws Exception {
34
		// TODO Auto-generated method stub
35
		return false;
36
	}
37
38
	/**
39
	 * 清除
40
	 */
41
	public void clear() throws Exception {
42
		// TODO Auto-generated method stub
43
		
44
	}
45
46
	/**
47
	 * key是否存在
48
	 */
49
	public boolean keyExists(String cacheKey) {
50
		// TODO Auto-generated method stub
51
		return false;
52
	}
53
54
	/**
55
	 * 在缓存中存放一个K-V键值对,同名键会被覆盖。设置多少秒后超时
56
	 */
57
	public boolean put(Object key, Object value, int secondTimeout)
58
			throws Exception {
59
		// TODO Auto-generated method stub
60
		return false;
61
	}
62
63
	/**
64
	 * 递增计数器(线程安全),步长为1。
65
	 */
66
	public long incr(String cacheKey) {
67
		// TODO Auto-generated method stub
68
		return 0;
69
	}
70
71
	/**
72
	 * 递增计数器(线程安全),步长为inc。
73
	 */
74
	public long incr(String cacheKey, int inc) {
75
		// TODO Auto-generated method stub
76
		return 0;
77
	}
78
79
	/**
80
	 * 递减计数器(线程安全), 步长为1。
81
	 */
82
	public long decr(String cacheKey) {
83
		// TODO Auto-generated method stub
84
		return 0;
85
	}
86
87
	/**
88
	 * 递减计数器(线程安全), 步长为inc。
89
	 */
90
	public long decr(String cacheKey, int inc) {
91
		// TODO Auto-generated method stub
92
		return 0;
93
	}
94
95
}

+ 111 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/mem/impl/WadeMemCache.java

@ -0,0 +1,111 @@
1
package com.ai.ipu.cache.mem.impl;
2
3
import com.ai.ipu.cache.mem.IMemCache;
4
5
/**
6
 * wade MemCache实现
7
 */
8
public class WadeMemCache implements IMemCache{
9
	private com.ailk.cache.memcache.interfaces.IMemCache memCache;
10
11
	/**
12
	 * 构造器
13
	 * @param memCache 代理的对象
14
	 */
15
	public WadeMemCache(com.ailk.cache.memcache.interfaces.IMemCache memCache){
16
		this.memCache = memCache;
17
	}
18
19
	/**
20
	 * 存储数据
21
     * @return 是否存储成功
22
	 */
23
	public boolean put(Object key, Object value) throws Exception {
24
		// TODO Auto-generated method stub
25
		return memCache.set((String) key, value);
26
	}
27
28
	/**
29
	 * 取
30
     * @return 对应的缓存结果
31
	 */
32
	public Object get(Object key) throws Exception {
33
		// TODO Auto-generated method stub
34
		return memCache.get((String) key);
35
	}
36
37
	/**
38
	 * 移除
39
     * @return 是否移除成功
40
	 */
41
	public boolean remove(Object key) throws Exception {
42
		// TODO Auto-generated method stub
43
		return memCache.delete((String) key);
44
	}
45
46
	/**
47
	 * 清除
48
	 */
49
	public void clear() throws Exception {
50
		// TODO Auto-generated method stub
51
		if(memCache!=null){
52
			((MemCache)memCache).clear();
53
		}
54
	}
55
56
	/**
57
	 * key是否存在
58
     * @return key是否存在
59
	 */
60
	public boolean keyExists(String cacheKey) {
61
		// TODO Auto-generated method stub
62
		return memCache.keyExists(cacheKey);
63
	}
64
65
	/**
66
	 * 在缓存中存放一个K-V键值对,同名键会被覆盖。设置多少秒后超时
67
     * @return 是否put成功
68
	 */
69
	public boolean put(Object key, Object value, int secondTimeout)
70
			throws Exception {
71
		// TODO Auto-generated method stub
72
		return memCache.set((String)key, value, secondTimeout);
73
	}
74
75
	/**
76
	 * 递增计数器(线程安全),步长为1。
77
	 * @return 增加的数值
78
	 */
79
	public long incr(String cacheKey) {
80
		// TODO Auto-generated method stub
81
		return memCache.incr(cacheKey);
82
	}
83
84
	/**
85
	 * 递增计数器(线程安全),步长为inc。
86
     * @return 增加的数值
87
	 */
88
	public long incr(String cacheKey, int inc) {
89
		// TODO Auto-generated method stub
90
		return memCache.incr(cacheKey, inc);
91
	}
92
93
	/**
94
	 * 递减计数器(线程安全), 步长为1。
95
     * @return 减少之后的数值
96
	 */
97
	public long decr(String cacheKey) {
98
		// TODO Auto-generated method stub
99
		return memCache.decr(cacheKey);
100
	}
101
102
	/**
103
	 * 递减计数器(线程安全), 步长为inc。
104
     * @return 减少之后的数值
105
	 */
106
	public long decr(String cacheKey, int inc) {
107
		// TODO Auto-generated method stub
108
		return memCache.decr(cacheKey, inc);
109
	}
110
111
}

+ 140 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/IRedisCache.java

@ -0,0 +1,140 @@
1
package com.ai.ipu.cache.redis;
2
3
import java.util.List;
4
import java.util.Map;
5
import java.util.Set;
6
7
import com.ai.ipu.cache.ICache;
8
import com.ai.ipu.cache.redis.listener.AbstractPubSubListener;
9
10
/**
11
 * redis缓存接口
12
 */
13
public interface IRedisCache extends ICache{
14
    /**
15
     *  自增
16
     * @param key
17
     * @return 自增之后的值
18
     */
19
    public Long incr(String key);
20
21
    /**
22
     * 自定义步长自增
23
     * @param key
24
     * @param step
25
     * @return 增长之后的值
26
     */
27
    public Long incrBy(String key, long step);
28
29
    /**
30
     * 设置失效时间
31
     * @param key
32
     * @param timeoutSeconds
33
     * @return 过期失效时间
34
     */
35
    public Long expire(String key, int timeoutSeconds);
36
37
    /**
38
     * 设置失效时间点
39
     * @param key
40
     * @param millisSeconds
41
     * @return 过期失效时间
42
     */
43
    public Long expireAt(String key, long millisSeconds);
44
45
    /**
46
     * 设置数据
47
     * @param key 键
48
     * @param value 值
49
     * @param timeoutSeconds 过期时间
50
     * @return 是否存储成功
51
     * @throws Exception
52
     */
53
    public boolean put(Object key, Object value, int timeoutSeconds) throws Exception;
54
55
    /**
56
     * 设置map
57
     * @param key 键
58
     * @param map 映射
59
     * @return 是否存储成功
60
     */
61
    public boolean putMap(String key, Map<String,String> map);
62
63
    /**
64
     * 设置单个key value
65
     * @param key 键
66
     * @param element 映射的key
67
     * @param value 值
68
     * @return 是否存储成功
69
     */
70
    public boolean putMapElement(String key, String element, String value);
71
72
    /**
73
     * 获取map的长度
74
     * @param key 键
75
     * @return 映射的长度
76
     */
77
    public long getMapLens(String key);
78
79
    /**
80
     * 获取map中所有的key
81
     * @param key 键
82
     * @return 对应映射的键集
83
     */
84
    public Set<String> getMapKeys(String key);
85
86
    /**
87
     * 获取map中所有的value
88
     * @param key 键
89
     * @return 对应映射的值集
90
     */
91
    public List<String> getMapVals(String key);
92
93
    /**
94
     * 获取map中的value
95
     * @param key 键
96
     * @param fields 映射的keys
97
     * @return 值集
98
     */
99
    public List<String> takeMapVals(String key, String... fields);
100
101
    /**
102
     * 删除map中的value
103
     * @param key 键
104
     * @param elements 映射的keys
105
     * @return 是否删除成功
106
     */
107
    public boolean delMapElement(String key, String... elements);
108
109
    /**
110
     * 判断map中的element是否存在
111
     * @param key 键
112
     * @param element 映射的key
113
     * @return 是否存在
114
     */
115
    public boolean mapElementExist(String key, String element);
116
    
117
    /**
118
     * 进行资源回收
119
     * @throws Exception
120
     */
121
    public void close() throws Exception;
122
    
123
    /**
124
     * publish消息,仅支持发布字符串或字节型数组
125
     * 
126
     * @param channel
127
     * @param message
128
     * @return -1:非字符串或字节型数组,发布失败;-2:channel为空,发布失败;-3:message为空,发布失败
129
     * >=0 接收消息的订阅者数量
130
     * @throws Exception
131
     */
132
    public Long publish(Object channel, Object message) throws Exception;
133
    
134
    /**
135
     * @param listener
136
     * @param channels
137
     * @throws Exception
138
     */
139
    public void subscribe(AbstractPubSubListener listener, String... channels) throws Exception;
140
}

+ 182 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/RedisCacheFactory.java

@ -0,0 +1,182 @@
1
package com.ai.ipu.cache.redis;
2
3
import java.util.HashSet;
4
import java.util.List;
5
import java.util.Map;
6
import java.util.Set;
7
import java.util.concurrent.locks.ReentrantLock;
8
9
import org.jsoup.helper.StringUtil;
10
11
import redis.clients.jedis.HostAndPort;
12
import redis.clients.jedis.Jedis;
13
import redis.clients.jedis.JedisCluster;
14
import redis.clients.jedis.JedisPool;
15
import redis.clients.jedis.JedisPoolConfig;
16
17
import com.ai.ipu.cache.config.IpuCacheConfig;
18
import com.ai.ipu.cache.util.IpuCacheConstant;
19
20
/**
21
 * redis缓存工厂类
22
 */
23
public class RedisCacheFactory {
24
    private static JedisPool pool;
25
    private static final int DEFAULT_POOL_SIZE = 8;
26
    private static final int DEFAULT_MAX_IDLE = 8;
27
    private static final int DEFAULT_MIN_IDLE = 1;
28
    private static final int DEFAULT_SO_TIMEOUT = 5000;
29
    private static final int DEFAULT_CONN_TIMEOUT = 5000;
30
    private static final int DEFAULT_MAX_ATTEMPTS = 3;
31
    protected static ReentrantLock reLock = new ReentrantLock();
32
    
33
    private RedisCacheFactory() {
34
    }
35
36
    /**
37
     * 获取redis 集群管理类
38
     * @param cacheName 相应的配置项的名称
39
     * @return redis集群管理类
40
     * @throws Exception
41
     */
42
    public static JedisCluster getJedisCluster(String cacheName) throws Exception{
43
        String clientType = IpuCacheConfig.getCacheDefaultAttr(cacheName, 
44
                IpuCacheConstant.Redis.CLIENT_TYPE, IpuCacheConstant.ClientType.JEDIS_CLUSTER_CLIENT);
45
        //异常:"JedisCluster连接池中没有可用的连接,请确认缓存地址是否配置正确、缓存是否开启!"
46
        if(!IpuCacheConstant.ClientType.JEDIS_CLUSTER_CLIENT.equals(clientType)){
47
            return null;
48
        }else{
49
            return createJedisCluster(cacheName);
50
        }
51
    }
52
53
    public static JedisCluster createJedisCluster(String cacheName) throws Exception {
54
        List<Map<String,String>> clusterList = IpuCacheConfig.getCacheServers(cacheName);
55
        if (null == clusterList || clusterList.isEmpty())
56
            throw new IllegalArgumentException("请确认server是否配置正确");
57
        
58
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
59
        Map<String, String> server; 
60
        for (int i = 0; i < clusterList.size(); i++) {
61
            server = clusterList.get(i);
62
            nodes.add(new HostAndPort(server.get(IpuCacheConstant.Redis.IP), 
63
                    Integer.parseInt(server.get(IpuCacheConstant.Redis.PORT))));
64
        }
65
        
66
        
67
        JedisPoolConfig config = createPool(cacheName);
68
        /*设置其他参数*/
69
        int soTimeout   = DEFAULT_SO_TIMEOUT;
70
        int connTimeout = DEFAULT_CONN_TIMEOUT;
71
        int maxAttempts = DEFAULT_MAX_ATTEMPTS;
72
        String strSoTimeout = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.SO_TIMEOUT);
73
        String strConnTimeout = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.CONN_TIMEOUT);
74
        String strMaxAttempts = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.MAX_ATTEMPS);
75
        if (!StringUtil.isBlank(strSoTimeout)){
76
            soTimeout = Integer.parseInt(strSoTimeout);
77
        }
78
        if (!StringUtil.isBlank(strConnTimeout)){
79
            connTimeout = Integer.parseInt(strConnTimeout);
80
        }
81
        if (!StringUtil.isBlank(strMaxAttempts)){
82
            maxAttempts = Integer.parseInt(strMaxAttempts);
83
        }
84
        
85
        JedisCluster jedisCluster;
86
        String auth = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.AUTH);
87
        if (StringUtil.isBlank(auth)){
88
            jedisCluster = new JedisCluster(nodes, connTimeout, maxAttempts, config);
89
        }else{
90
            jedisCluster = new JedisCluster(nodes, connTimeout, soTimeout, maxAttempts, auth,  config);
91
        }
92
        return jedisCluster;
93
    }
94
    
95
    public static Jedis getJedis(String cacheName) throws Exception{
96
        String clientType = IpuCacheConfig.getCacheDefaultAttr(cacheName, 
97
                IpuCacheConstant.Redis.CLIENT_TYPE, IpuCacheConstant.ClientType.JEDIS_CLIENT);
98
        //异常:"Jedis连接池中没有可用的连接,请确认缓存地址是否配置正确、缓存是否开启!"
99
        if(!IpuCacheConstant.ClientType.JEDIS_CLIENT.equals(clientType)){
100
            return null;
101
        }else{
102
        	assert ! reLock.isHeldByCurrentThread();  
103
            reLock.lock();
104
            try {
105
                JedisPool pool = getJedisPool(cacheName);
106
                return pool.getResource();
107
            }finally {
108
            	reLock.unlock(); 
109
            }
110
        }
111
    }
112
    
113
    public static JedisPool getJedisPool(String cacheName) throws Exception{
114
        if(pool==null){
115
            pool = createJedisPool(cacheName);
116
        }
117
        return pool;
118
    }
119
120
    private static JedisPool createJedisPool(String cacheName) throws Exception {
121
        List<Map<String,String>> clusterList = IpuCacheConfig.getCacheServers(cacheName);
122
        if (null == clusterList || clusterList.isEmpty())
123
            throw new IllegalArgumentException("请确认server是否配置正确");
124
        //只取第一个redis地址
125
        Map<String, String> server = clusterList.get(0);        
126
        
127
        JedisPoolConfig config = createPool(cacheName);
128
        /*设置其他参数*/
129
        int connTimeout = DEFAULT_CONN_TIMEOUT;
130
        String strConnTimeout = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.CONN_TIMEOUT);
131
        if (!StringUtil.isBlank(strConnTimeout)){
132
            connTimeout = Integer.parseInt(strConnTimeout);
133
        }
134
        
135
        String host = server.get(IpuCacheConstant.Redis.IP);
136
        int port = Integer.parseInt(server.get(IpuCacheConstant.Redis.PORT));
137
        String auth = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.AUTH);
138
        if (StringUtil.isBlank(auth)){
139
            pool = new JedisPool(config, host, port, connTimeout);
140
        }else{
141
            pool = new JedisPool(config, host, port, connTimeout, auth);
142
        }
143
144
        return pool;
145
    }
146
    
147
    private static JedisPoolConfig createPool(String cacheName) throws Exception {
148
        JedisPoolConfig config = new JedisPoolConfig();
149
        /*连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true*/
150
        config.setBlockWhenExhausted(false);
151
        /*默认值设置*/
152
        int poolSize = DEFAULT_POOL_SIZE;
153
        int maxIdle  = DEFAULT_MAX_IDLE;
154
        int minIdle  = DEFAULT_MIN_IDLE;
155
        
156
        String strPoolSize = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.POOL_SIZE);
157
        String strMaxIdle = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.MAX_IDLE);
158
        String strMinIdle = IpuCacheConfig.getCacheAttr(cacheName, IpuCacheConstant.Redis.MIN_IDLE);        
159
        
160
        /*设置JedisPoolConfig参数*/
161
        if(!StringUtil.isBlank(strPoolSize)){
162
            poolSize = Integer.parseInt(strPoolSize);
163
        }
164
        if (!StringUtil.isBlank(strMaxIdle)){
165
            maxIdle = Integer.parseInt(strMaxIdle);
166
        }
167
        if (!StringUtil.isBlank(strMinIdle)){
168
            minIdle = Integer.parseInt(strMinIdle);
169
        }
170
        //最大连接数, 应用自己评估,不要超过ApsaraDB for Redis每个实例最大的连接数
171
        config.setMaxTotal(poolSize);
172
        
173
        //最大空闲连接数, 应用自己评估,不要超过ApsaraDB for Redis每个实例最大的连接数
174
        config.setMaxIdle(maxIdle);
175
        config.setMinIdle(minIdle);
176
        config.setTestOnBorrow(false);
177
        config.setTestOnReturn(false);
178
        config.setTestWhileIdle(true);
179
        
180
        return config;
181
    }
182
}

+ 305 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/impl/JedisCache.java

@ -0,0 +1,305 @@
1
package com.ai.ipu.cache.redis.impl;
2
3
import java.util.ArrayList;
4
import java.util.Comparator;
5
import java.util.List;
6
import java.util.Map;
7
import java.util.Set;
8
import java.util.TreeSet;
9
10
import redis.clients.jedis.Jedis;
11
12
import com.ai.ipu.basic.string.StringUtil;
13
import com.ai.ipu.basic.util.serial.DefaultSerializable;
14
import com.ai.ipu.basic.util.serial.ISerializable;
15
import com.ai.ipu.cache.redis.IRedisCache;
16
import com.ai.ipu.cache.redis.listener.AbstractPubSubListener;
17
import com.ailk.org.apache.commons.lang3.ArrayUtils;
18
19
/**
20
 * redis缓存的实现
21
 */
22
public class JedisCache implements IRedisCache {
23
    private Jedis redisCache;
24
    /**
25
     * 对象序列化与反序列化接口。
26
     */
27
    private static final ISerializable SERIALIZER = new DefaultSerializable();
28
    
29
    public JedisCache(Jedis jedis)
30
    {
31
        this.redisCache = jedis;
32
    }
33
34
    /**
35
     * 存
36
     */
37
    @Override
38
    public boolean put(Object key, Object value) throws Exception {
39
        String result = "";
40
        if (key instanceof String)
41
            result = redisCache.set(key.toString().getBytes(), SERIALIZER.encode(value));
42
        else if (key instanceof byte[])
43
            result = redisCache.set((byte[])key, (byte[])value);
44
        
45
        if ("OK".equalsIgnoreCase(result))
46
            return true;
47
        else
48
            return false;
49
    }
50
51
    /**
52
     * 取
53
     */
54
    @Override
55
    public Object get(Object key) throws Exception {
56
        // TODO Auto-generated method stub        
57
        if (key instanceof String)
58
        {
59
            if (StringUtil.isEmpty((String)key))
60
                return null;
61
            return SERIALIZER.decode(redisCache.get(key.toString().getBytes()));
62
        }
63
        else if (key instanceof byte[])
64
            return redisCache.get((byte[])key);
65
        return null;
66
    }
67
68
    /**
69
     * 移除
70
     */
71
    @Override
72
    public boolean remove(Object key) throws Exception {
73
        long result = -1;
74
        if (key instanceof String)
75
            result = redisCache.del((String)key);
76
        else if (key instanceof byte[])
77
            result = redisCache.del((byte[])key);
78
        return result == 1?true:false;
79
    }
80
81
    /**
82
     * 清除
83
     */
84
    @Override
85
    public void clear() throws Exception {
86
        redisCache.flushDB();
87
    }
88
89
    /**
90
     * key是否存在
91
     */
92
    @Override
93
    public boolean keyExists(String cacheKey) {
94
        return redisCache.exists(cacheKey.toString());
95
    }
96
97
    /**
98
     *  自增
99
     * @param key
100
     * @return
101
     */
102
    @Override
103
    public Long incr(String key) {
104
        return redisCache.incr(key);
105
    }
106
107
    /**
108
     * 自定义步长自增
109
     * @param key
110
     * @param step
111
     * @return
112
     */
113
    @Override
114
    public Long incrBy(String key, long step) {
115
        return redisCache.incrBy(key, step);
116
    }
117
118
    /**
119
     * 设置失效时间
120
     * @param key
121
     * @param timeoutSeconds
122
     * @return
123
     */
124
    @Override
125
    public Long expire(String key, int timeoutSeconds) {
126
        return redisCache.expire(key, timeoutSeconds);
127
    }
128
129
    /**
130
     * 设置失效时间点
131
     * @param key
132
     * @param millisSeconds
133
     * @return
134
     */
135
    @Override
136
    public Long expireAt(String key, long millisSeconds) {
137
        return redisCache.expireAt(key, millisSeconds);
138
    }
139
140
    /**
141
     * 设置数据
142
     * @param key
143
     * @param value
144
     * @param timeoutSeconds
145
     * @return
146
     * @throws Exception
147
     */
148
    @Override
149
    public boolean put(Object key, Object value, int timeoutSeconds) throws Exception {
150
        String result = "";
151
        if (key instanceof String)
152
            result = redisCache.setex(key.toString().getBytes(), timeoutSeconds, SERIALIZER.encode(value));
153
        else if (key instanceof byte[])
154
            result = redisCache.setex((byte[])key, timeoutSeconds, (byte[])value);
155
        
156
        if ("OK".equalsIgnoreCase(result))
157
            return true;
158
        else
159
            return false;
160
    }
161
162
    /**
163
     * 设置map
164
     * @param key
165
     * @param map
166
     * @return
167
     */
168
    @Override
169
    public boolean putMap(String key, Map<String, String> map) {
170
        String result = redisCache.hmset(key, map);
171
        if ("OK".equalsIgnoreCase(result))
172
            return true;
173
        else
174
            return false;
175
    }
176
177
    /**
178
     * 获取map的长度
179
     * @param key
180
     * @return
181
     */
182
    @Override
183
    public long getMapLens(String key) {
184
        // TODO Auto-generated method stub
185
        return redisCache.hlen(key);
186
    }
187
188
    /**
189
     * 获取map中所有的key
190
     * @param key
191
     * @return
192
     */
193
    @Override
194
    public Set<String> getMapKeys(String key) {
195
        Set<String> result = new TreeSet<String>(new MyComparator());
196
        result.addAll(redisCache.hkeys(key));
197
        return result;
198
    }
199
200
    /**
201
     * 获取map中所有的value
202
     * @param key
203
     * @return
204
     */
205
    @Override
206
    public List<String> getMapVals(String key) {
207
        return redisCache.hvals(key);
208
    }
209
210
    /**
211
     * 获取map中的value
212
     * @param key
213
     * @param fields
214
     * @return
215
     */
216
    @Override
217
    public List<String> takeMapVals(String key, String... fields) {
218
        if (keyExists(key))
219
            return redisCache.hmget(key, fields);
220
        else
221
            return new ArrayList<String>();
222
    }
223
224
    /**
225
     * 删除map中的value
226
     * @param key
227
     * @param elements
228
     * @return
229
     */
230
    @Override
231
    public boolean delMapElement(String key, String... elements) {
232
        long result = redisCache.hdel(key, elements);
233
        return result == 1?true:false;
234
    }
235
236
    /**
237
     * 设置单个key value
238
     * @param key
239
     * @param element
240
     * @param value
241
     * @return
242
     */
243
    @Override
244
    public boolean putMapElement(String key, String element, String value) {
245
        long result = redisCache.hset(key, element, value);
246
        return result == 1?true:false;
247
    }
248
249
    /**
250
     * 判断map中的element是否存在
251
     * @param key
252
     * @param element
253
     * @return
254
     */
255
    @Override
256
    public boolean mapElementExist(String key, String element) {
257
        return redisCache.hexists(key, element);
258
    }
259
260
    /**
261
     * 自定义比较器
262
     */
263
    class MyComparator implements Comparator<String>{  
264
          
265
        @Override  
266
        public int compare(String o1, String o2) {                
267
            return o2.compareTo(o1);//降序排列  
268
        }  
269
          
270
    }
271
272
    @Override
273
    public void close() throws Exception {
274
        redisCache.close();
275
    }
276
277
    @Override
278
    public Long publish(Object channel, Object message) throws Exception {
279
        if (channel instanceof String)
280
        {
281
            if (StringUtil.isEmpty((String)channel))
282
                return -2l;
283
            if (StringUtil.isEmpty((String)message))
284
                return -3l;
285
            return redisCache.publish((String)channel, (String)message);
286
        }
287
        else if (channel instanceof byte[])
288
        {
289
            if (!ArrayUtils.isEmpty((byte[]) channel))
290
                if (!ArrayUtils.isEmpty((byte[]) message))
291
                    return redisCache.publish((byte[])channel, (byte[])message);
292
                else
293
                    return -3l;
294
            else
295
                return -2l;
296
        }
297
        return -1l;
298
        
299
    }
300
    
301
    @Override
302
    public void subscribe(AbstractPubSubListener listener, String... channels) throws Exception{
303
        redisCache.subscribe(listener, channels);
304
    }
305
}

+ 300 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/impl/JedisClusterCache.java

@ -0,0 +1,300 @@
1
package com.ai.ipu.cache.redis.impl;
2
3
import java.util.ArrayList;
4
import java.util.Comparator;
5
import java.util.List;
6
import java.util.Map;
7
import java.util.Set;
8
import java.util.TreeSet;
9
10
import redis.clients.jedis.JedisCluster;
11
12
import com.ai.ipu.basic.string.StringUtil;
13
import com.ai.ipu.basic.util.serial.DefaultSerializable;
14
import com.ai.ipu.basic.util.serial.ISerializable;
15
import com.ai.ipu.cache.redis.IRedisCache;
16
import com.ai.ipu.cache.redis.listener.AbstractPubSubListener;
17
import com.ailk.org.apache.commons.lang3.ArrayUtils;
18
19
/**
20
 * redis缓存的实现
21
 */
22
public class JedisClusterCache implements IRedisCache {
23
    private JedisCluster redisCache;
24
    /**
25
     * 对象序列化与反序列化接口。
26
     */
27
    private static final ISerializable SERIALIZER = new DefaultSerializable();
28
    
29
    public JedisClusterCache(JedisCluster jedisCluster)
30
    {
31
        this.redisCache = jedisCluster;
32
    }
33
34
    /**
35
     * 存
36
     */
37
    @Override
38
    public boolean put(Object key, Object value) throws Exception {
39
        String result = "";
40
        if (key instanceof String)
41
            result = redisCache.set(key.toString().getBytes(), SERIALIZER.encode(value));
42
        else if (key instanceof byte[])
43
            result = redisCache.set((byte[])key, (byte[])value);
44
        
45
        return "OK".equalsIgnoreCase(result);
46
    }
47
48
    /**
49
     * 取
50
     */
51
    @Override
52
    public Object get(Object key) throws Exception {
53
        if (key instanceof String)
54
        {
55
            if (StringUtil.isEmpty((String)key))
56
                return null;
57
            return SERIALIZER.decode(redisCache.get(key.toString().getBytes()));
58
        }
59
        else if (key instanceof byte[])
60
            return redisCache.get((byte[])key);
61
        return null;
62
    }
63
64
    /**
65
     * 移除
66
     */
67
    @Override
68
    public boolean remove(Object key) throws Exception {
69
        long result = -1;
70
        if (key instanceof String)
71
            result = redisCache.del((String)key);
72
        else if (key instanceof byte[])
73
            result = redisCache.del((byte[])key);
74
        return result == 1?true:false;
75
    }
76
77
    /**
78
     * 清除
79
     */
80
    @Override
81
    public void clear() throws Exception {
82
        //集群不支持clear
83
        throw new Exception("集群不支持clear");
84
    }
85
86
    /**
87
     * key是否存在
88
     */
89
    @Override
90
    public boolean keyExists(String cacheKey) {
91
        return redisCache.exists(cacheKey);
92
    }
93
94
    /**
95
     *  自增
96
     * @param key
97
     * @return
98
     */
99
    @Override
100
    public Long incr(String key) {
101
        return redisCache.incr(key);
102
    }
103
104
    /**
105
     * 自定义步长自增
106
     * @param key
107
     * @param step
108
     * @return
109
     */
110
    @Override
111
    public Long incrBy(String key, long step) {
112
        return redisCache.incrBy(key, step);
113
    }
114
115
    /**
116
     * 设置失效时间
117
     * @param key
118
     * @param timeoutSeconds
119
     * @return
120
     */
121
    @Override
122
    public Long expire(String key, int timeoutSeconds) {
123
        return redisCache.expire(key, timeoutSeconds);
124
    }
125
126
    /**
127
     * 设置失效时间点
128
     * @param key
129
     * @param millisSeconds
130
     * @return
131
     */
132
    @Override
133
    public Long expireAt(String key, long millisSeconds) {
134
        return redisCache.expireAt(key, millisSeconds);
135
    }
136
137
    /**
138
     * 设置数据
139
     * @param key
140
     * @param value
141
     * @param timeoutSeconds
142
     * @return
143
     * @throws Exception
144
     */
145
    @Override
146
    public boolean put(Object key, Object value, int timeoutSeconds) throws Exception {
147
        String result = "";
148
        if (key instanceof String)
149
            result = redisCache.setex(key.toString().getBytes(), timeoutSeconds, SERIALIZER.encode(value));
150
        else if (key instanceof byte[])
151
            result = redisCache.setex((byte[])key, timeoutSeconds, (byte[])value);
152
        
153
        return "OK".equalsIgnoreCase(result);
154
    }
155
156
    /**
157
     * 设置map
158
     * @param key
159
     * @param map
160
     * @return
161
     */
162
    @Override
163
    public boolean putMap(String key, Map<String, String> map) {
164
        String result = redisCache.hmset(key, map);
165
        return "OK".equalsIgnoreCase(result);
166
    }
167
168
    /**
169
     * 获取map的长度
170
     * @param key
171
     * @return
172
     */
173
    @Override
174
    public long getMapLens(String key) {
175
        return redisCache.hlen(key);
176
    }
177
178
    /**
179
     * 获取map中所有的key
180
     * @param key
181
     * @return
182
     */
183
    @Override
184
    public Set<String> getMapKeys(String key) {
185
        Set<String> result = new TreeSet<String>(new MyComparator());
186
        result.addAll(redisCache.hkeys(key));
187
        return result;
188
    }
189
190
    /**
191
     * 获取map中所有的value
192
     * @param key
193
     * @return
194
     */
195
    @Override
196
    public List<String> getMapVals(String key) {
197
        return redisCache.hvals(key);
198
    }
199
200
    /**
201
     * 获取map中的value
202
     * @param key
203
     * @param fields
204
     * @return
205
     */
206
    @Override
207
    public List<String> takeMapVals(String key, String... fields) {
208
        if (keyExists(key))
209
            return redisCache.hmget(key, fields);
210
        else
211
            return new ArrayList<String>();
212
    }
213
214
    /**
215
     * 删除map中的value
216
     * @param key
217
     * @param elements
218
     * @return
219
     */
220
    @Override
221
    public boolean delMapElement(String key, String... elements) {
222
        long result = redisCache.hdel(key, elements);
223
        return result == 1;
224
    }
225
226
    /**
227
     * 设置单个key value
228
     * @param key
229
     * @param element
230
     * @param value
231
     * @return
232
     */
233
    @Override
234
    public boolean putMapElement(String key, String element, String value) {
235
        long result = redisCache.hset(key, element, value);
236
        return result == 1?true:false;
237
    }
238
239
    /**
240
     * 判断map中的element是否存在
241
     * @param key
242
     * @param element
243
     * @return
244
     */
245
    @Override
246
    public boolean mapElementExist(String key, String element) {
247
        return redisCache.hexists(key, element);
248
    }
249
250
    /**
251
     * 自定义比较器
252
     */
253
    class MyComparator implements Comparator<String>{  
254
          
255
        @Override  
256
        public int compare(String o1, String o2) {                
257
            return o2.compareTo(o1);//降序排列  
258
        }  
259
          
260
    }
261
262
    /* (non-Javadoc)
263
     * 集群单例模式不需要close
264
     * @see com.ai.ipu.cache.redis.IRedisCache#close()
265
     */
266
    @Override
267
    public void close() throws Exception {
268
        //redisCache.close();
269
    }
270
271
    @Override
272
    public Long publish(Object channel, Object message) throws Exception {
273
        if (channel instanceof String)
274
        {
275
            if (StringUtil.isEmpty((String)channel))
276
                return -2l;
277
            if (StringUtil.isEmpty((String)message))
278
                return -3l;
279
            return redisCache.publish((String)channel, (String)message);
280
        }
281
        else if (channel instanceof byte[])
282
        {
283
        	if (!ArrayUtils.isEmpty((byte[]) channel))
284
                if (!ArrayUtils.isEmpty((byte[]) message))
285
                    return redisCache.publish((byte[])channel, (byte[])message);
286
                else
287
                    return -3l;
288
            else
289
                return -2l;
290
        }
291
        return -1l;
292
        
293
    }
294
    
295
    @Override
296
    public void subscribe(AbstractPubSubListener listener, String... channels) throws Exception{
297
        redisCache.subscribe(listener, channels);
298
    }
299
300
}

+ 15 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/redis/listener/AbstractPubSubListener.java

@ -0,0 +1,15 @@
1
package com.ai.ipu.cache.redis.listener;
2
3
import redis.clients.jedis.JedisPubSub;
4
5
public abstract class AbstractPubSubListener extends JedisPubSub {
6
	// 取得订阅的消息后的处理  
7
    public abstract void onMessage(String channel, String message);
8
9
    // 初始化订阅时候的处理  
10
    public abstract void onSubscribe(String channel, int subscribedChannels);
11
12
    // 取消订阅时候的处理  
13
    public abstract void onUnsubscribe(String channel, int subscribedChannels);
14
15
}

+ 33 - 0
ipu-redis-example/src/main/java/com/ai/ipu/cache/util/IpuCacheConstant.java

@ -0,0 +1,33 @@
1
package com.ai.ipu.cache.util;
2
3
/**
4
 * ipu-cache常量工具类
5
 *
6
 * @author huangbo@asiainfo.com
7
 */
8
public class IpuCacheConstant {
9
    
10
    private IpuCacheConstant() {}
11
12
    public static class Redis{
13
        public static final String CLIENT_TYPE = "clientType";
14
        public static final String AUTH = "auth";
15
        public static final String POOL_SIZE = "poolSize";
16
        public static final String MAX_IDLE = "maxIdle";
17
        public static final String MIN_IDLE = "minIdle";
18
        public static final String SO_TIMEOUT = "soTimeout";
19
        public static final String CONN_TIMEOUT = "connTimeout";
20
        public static final String MAX_ATTEMPS = "maxAttempts";        
21
        public static final String IP = "ip";
22
        public static final String PORT = "port";
23
        
24
        private Redis() {}
25
    }
26
    
27
    public static class ClientType{
28
        public static final String JEDIS_CLIENT = "Jedis";
29
        public static final String JEDIS_CLUSTER_CLIENT = "JedisCluster";
30
        
31
        private ClientType() {}
32
    }
33
}

+ 67 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/CacheFactoryTest.java

@ -0,0 +1,67 @@
1
package com.ai.ipu.cache;
2
3
import com.ai.ipu.basic.log.ILogger;
4
import com.ai.ipu.basic.log.IpuLoggerFactory;
5
import com.ai.ipu.cache.CacheFactory.CacheType;
6
7
import junit.framework.TestCase;
8
9
public class CacheFactoryTest extends TestCase{
10
    private static final transient ILogger LOGGER = IpuLoggerFactory.createLogger(CacheFactoryTest.class);
11
    private static final String STR_VALUE = "12345";
12
    private static final String STR_KEY = "key";
13
    private static final String CACHE_NAME = "data";
14
    private static final String CLUSTER_CACHE_NAME = "ssn";
15
    
16
    public void testGetCache() throws Exception {
17
        ICache cache = CacheFactory.getCache(CACHE_NAME);
18
        LOGGER.debug((String)cache.get(STR_KEY));
19
        cache.put(STR_KEY, STR_VALUE);
20
        LOGGER.debug((String)cache.get(STR_KEY));
21
        assertEquals(STR_VALUE, cache.get(STR_KEY));
22
        cache.remove(STR_KEY);
23
        
24
        cache = CacheFactory.getCache(CacheType.redis, CACHE_NAME);
25
        LOGGER.debug((String)cache.get(STR_KEY));
26
        cache.put(STR_KEY, STR_VALUE);
27
        LOGGER.debug((String)cache.get(STR_KEY));
28
        assertEquals(STR_VALUE, cache.get(STR_KEY));
29
        cache.remove(STR_KEY);
30
        
31
        CacheFactory.close(CACHE_NAME, cache);
32
        
33
        cache = CacheFactory.getCache(CacheType.redis, CACHE_NAME);
34
        LOGGER.debug((String)cache.get(STR_KEY));
35
        cache.put(STR_KEY, STR_VALUE);
36
        LOGGER.debug((String)cache.get(STR_KEY));
37
        assertEquals(STR_VALUE, cache.get(STR_KEY));
38
        cache.remove(STR_KEY);
39
        CacheFactory.close(CACHE_NAME, cache);
40
    }
41
    
42
    public void testAuthFailed() {
43
        try {
44
            CacheFactory.getCache(CACHE_NAME);
45
            assertFalse("校验成功", true);
46
        } catch (Exception e) {
47
            LOGGER.debug(e.getMessage());
48
            assertEquals("NOAUTH Authentication required.", e.getMessage());;
49
        }
50
    }
51
    
52
    public void testGetClusterCache() throws Exception {
53
        ICache cache = CacheFactory.getCache(CLUSTER_CACHE_NAME);
54
        LOGGER.debug((String)cache.get(STR_KEY));
55
        cache.put(STR_KEY, STR_VALUE);
56
        LOGGER.debug((String)cache.get(STR_KEY));
57
        assertEquals(STR_VALUE, cache.get(STR_KEY));
58
        cache.remove(STR_KEY);
59
        
60
        cache = CacheFactory.getCache(CacheType.redis, CLUSTER_CACHE_NAME);
61
        LOGGER.debug((String)cache.get(STR_KEY));
62
        cache.put(STR_KEY, STR_VALUE);
63
        LOGGER.debug((String)cache.get(STR_KEY));
64
        assertEquals(STR_VALUE, cache.get(STR_KEY));
65
        
66
    }
67
}

+ 46 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/config/IpuCacheConfigTest.java

@ -0,0 +1,46 @@
1
package com.ai.ipu.cache.config;
2
3
import java.util.List;
4
import java.util.Map;
5
6
import junit.framework.TestCase;
7
8
public class IpuCacheConfigTest extends TestCase{
9
10
    @Override
11
    protected void setUp() throws Exception {
12
        // TODO Auto-generated method stub
13
        super.setUp();
14
    }
15
    
16
    public void testGetCacheEntity() throws Exception {
17
        // TODO Auto-generated method stub
18
        System.out.println(IpuCacheConfig.getCacheEntity("ssn"));
19
        System.out.println(IpuCacheConfig.getCacheEntity("data"));
20
        assertTrue("执行成功", true);
21
    }
22
    
23
    public void testGetCacheServers() throws Exception {
24
        // TODO Auto-generated method stub
25
        List<Map<String,String>> ssnServers = IpuCacheConfig.getCacheServers("ssn");
26
        List<Map<String,String>> dataServers = IpuCacheConfig.getCacheServers("data");
27
        assertEquals(6, ssnServers.size());
28
        assertEquals(6, dataServers.size());
29
    }
30
    
31
    public void testGetCacheAttr() throws Exception {
32
        // TODO Auto-generated method stub
33
        assertEquals("JedisCluster" , IpuCacheConfig.getCacheAttr("ssn", "client"));
34
    }
35
    
36
    public void testGetCacheDefaultAttr() throws Exception {
37
        // TODO Auto-generated method stub
38
        assertEquals("Jedis" , IpuCacheConfig.getCacheDefaultAttr("data", "client", "Jedis"));
39
    }
40
    
41
    public void testGetCacheType() throws Exception {
42
        // TODO Auto-generated method stub
43
        assertEquals("redis" , IpuCacheConfig.getCacheType("ssn"));
44
    }
45
    
46
}

+ 24 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/mem/MemcacheTest.java

@ -0,0 +1,24 @@
1
package com.ai.ipu.cache.mem;
2
3
import junit.framework.TestCase;
4
5
import com.ai.ipu.cache.CacheFactory;
6
import com.ai.ipu.cache.CacheFactory.CacheType;
7
import com.ai.ipu.cache.mem.IMemCache;
8
9
public class MemcacheTest extends TestCase{
10
	
11
	/**
12
	 * 测试使用memcache的超时方式
13
	 * @throws Exception
14
	 */
15
	public void testSecondTimeout() throws Exception {
16
		// TODO Auto-generated method stub
17
		IMemCache cache = (IMemCache) CacheFactory.getCache(CacheType.wadeMem, "wade_cache");
18
		cache.put("wade_cache_key", "会超时的记录", 10);
19
		Thread.sleep(5000);
20
		System.out.println("5秒打印记录"+cache.get("wade_cache_key"));
21
		Thread.sleep(6000);
22
		System.out.println("11秒打印记录"+cache.get("wade_cache_key"));
23
	}
24
}

+ 69 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/JedisCacheTest.java

@ -0,0 +1,69 @@
1
package com.ai.ipu.cache.redis;
2
3
import com.ai.ipu.basic.log.ILogger;
4
import com.ai.ipu.basic.log.IpuLoggerFactory;
5
import com.ai.ipu.cache.CacheFactory;
6
import com.ai.ipu.cache.CacheFactory.CacheType;
7
import com.ai.ipu.cache.config.IpuCacheConfig;
8
import com.ai.ipu.cache.util.IpuCacheConstant;
9
10
import junit.framework.TestCase;
11
12
public class JedisCacheTest extends TestCase{
13
	private static final transient ILogger LOGGER = IpuLoggerFactory.createLogger(JedisCacheTest.class);
14
    private static final String STR_MESSAGE = "this is a test message";
15
    private static final String STR_VAL = "this is a test";
16
    private static final String STR_KEY = "key";
17
    private static final String CACHE_NAME = "data";
18
    private static final String STR_CHANNEL = "test";
19
    private static final long SECOND_TO_MS = 1000l;
20
    private static final int SLEEP_SECONDS = 3600;
21
    
22
    public void testPublish() throws Exception{
23
        IRedisCache cache = (IRedisCache)CacheFactory.getCache(CacheType.redis, CACHE_NAME);
24
        cache.publish(STR_CHANNEL, STR_MESSAGE);
25
    }
26
    
27
    public void testSubscribe()  throws Exception{
28
        IRedisCache cache = (IRedisCache)CacheFactory.getCache(CacheType.redis, CACHE_NAME);
29
        cache.subscribe(new PubSubListenerTest(), STR_CHANNEL);
30
        
31
        try{
32
            Thread.sleep(SLEEP_SECONDS * SECOND_TO_MS);
33
        }catch (Exception e)
34
        {
35
            
36
        }
37
        CacheFactory.close(CACHE_NAME, cache);
38
        
39
    }
40
    
41
    public void testPut() throws Exception{
42
        IRedisCache cache = null;
43
        try{
44
        	cache = (IRedisCache)CacheFactory.getCache(CacheType.redis, CACHE_NAME);
45
	        cache.put(STR_KEY, STR_VAL);
46
	        LOGGER.debug(STR_KEY+"="+cache.get(STR_KEY));
47
	        try{
48
	            Thread.sleep(10*SECOND_TO_MS);
49
	        }catch (Exception e)
50
	        {
51
	            ;
52
	        }
53
	        LOGGER.debug("after 10 seconds,"+STR_KEY+"="+cache.get(STR_KEY));
54
        }catch (Exception e)
55
        {
56
        	;
57
        }finally {
58
        	if (cache != null && IpuCacheConstant.ClientType.JEDIS_CLIENT.equalsIgnoreCase(IpuCacheConfig.getCacheDefaultAttr(CACHE_NAME,
59
                    IpuCacheConstant.Redis.CLIENT_TYPE, IpuCacheConstant.ClientType.JEDIS_CLIENT)))
60
        		cache.close();
61
        }
62
        
63
    }
64
    
65
    public void testClear() throws Exception{
66
        IRedisCache cache = (IRedisCache)CacheFactory.getCache(CacheType.redis, CACHE_NAME);
67
        cache.clear();
68
    }
69
}

+ 41 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/PubSubListenerTest.java

@ -0,0 +1,41 @@
1
package com.ai.ipu.cache.redis;
2
3
import com.ai.ipu.basic.log.ILogger;
4
import com.ai.ipu.basic.log.IpuLoggerFactory;
5
import com.ai.ipu.cache.redis.listener.AbstractPubSubListener;
6
7
public class PubSubListenerTest extends AbstractPubSubListener {
8
    private static final transient ILogger LOGGER = IpuLoggerFactory.createLogger(PubSubListenerTest.class);
9
    
10
    @Override
11
    public void onMessage(String channel, String message) {
12
        LOGGER.debug(String.format("receive redis published message, channel %s, message %s", channel, message));
13
    }
14
15
    @Override
16
    public void onSubscribe(String channel, int subscribedChannels) {
17
        LOGGER.debug(String.format("subscribe redis channel success, channel %s, subscribedChannels %d", 
18
                channel, subscribedChannels));
19
    }
20
21
    @Override
22
    public void onUnsubscribe(String channel, int subscribedChannels) {
23
        LOGGER.debug(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d", 
24
                channel, subscribedChannels));
25
26
    }
27
28
29
    public void onPSubscribe(String pattern, int subscribedChannels) {  
30
        LOGGER.debug(pattern + "=" + subscribedChannels);  
31
    }  
32
33
    public void onPUnsubscribe(String pattern, int subscribedChannels) {  
34
        LOGGER.debug(pattern + "=" + subscribedChannels);  
35
    }  
36
37
    public void onPMessage(String pattern, String channel, String message) {  
38
        LOGGER.debug(pattern + "=" + channel + "=" + message);  
39
    }  
40
41
}

+ 85 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/RedisCacheTest.java

@ -0,0 +1,85 @@
1
package com.ai.ipu.cache.redis;
2
3
import junit.framework.TestCase;
4
5
import com.ai.ipu.basic.log.ILogger;
6
import com.ai.ipu.basic.log.IpuLoggerFactory;
7
import com.ai.ipu.cache.CacheFactory;
8
import com.ai.ipu.cache.ICache;
9
import com.ai.ipu.cache.redis.context.IpuContextData;
10
import com.ai.ipu.cache.redis.context.IpuContextData2;
11
import com.alibaba.fastjson.JSON;
12
13
public class RedisCacheTest extends TestCase{
14
	private static final transient ILogger LOGGER = IpuLoggerFactory.createLogger(RedisCacheTest.class);
15
    private String cacheSingleName;
16
    private String cacheClusterName;
17
    private String cacheKey = "KEY";
18
    private String cacheContent = "CONTENT";
19
    private String strValue = "123456";
20
    private int intValue = 123456;
21
    
22
    @Override
23
    protected void setUp() throws Exception {
24
        // TODO Auto-generated method stub
25
        super.setUp();
26
        cacheSingleName = "single";
27
        cacheClusterName = "ssn";
28
    }
29
30
    public void testRedisSingle() throws Exception {
31
        // TODO Auto-generated method stub
32
        ICache cache = CacheFactory.getCache(cacheSingleName);
33
        cache.put(cacheKey, intValue);
34
//        LOGGER.debug(Integer.toString((Integer)cache.get(cacheKey)));
35
        System.out.println("cacheKey"+Integer.toString((Integer)cache.get(cacheKey)));
36
        System.out.println("cacheKey"+intValue);
37
        assertEquals(intValue, cache.get(cacheKey));
38
//        System.out.println();
39
    }
40
    
41
    public void testRedisCluster() throws Exception {
42
        // TODO Auto-generated method stub
43
        ICache cache = CacheFactory.getCache(cacheClusterName);
44
        cache.put(cacheKey, intValue);
45
        LOGGER.debug(Integer.toString((Integer)cache.get(cacheKey)));
46
        System.out.println(Integer.toString((Integer)cache.get(cacheKey)));
47
        System.out.println("cacheKey"+intValue);
48
        assertEquals(intValue, cache.get(cacheKey));
49
    }
50
    
51
    public void testObjectCache() throws Exception {
52
        // TODO Auto-generated method stub
53
        ICache cache = CacheFactory.getCache(cacheSingleName);
54
        IpuContextData contextData = new IpuContextData();
55
        contextData.put(cacheKey, strValue);
56
        cache.put(cacheContent, contextData);
57
        contextData = (IpuContextData) cache.get(cacheContent);
58
        System.out.println("strValue"+strValue);
59
        //cache.get(cacheKey) 对应的是存放缓存的hash值,其他取到的均为值等于123456的值
60
        System.out.println("cache中获取key值"+cache.get(cacheKey));
61
        System.out.println("contextData类中获取“KEY”的值"+contextData.getData().get("KEY"));
62
        assertEquals(strValue,contextData.get(cacheKey));
63
        System.out.println("=================");
64
        System.out.println(contextData.get("KEY"));
65
        assertEquals(contextData.getData().get("KEY"),strValue);
66
        System.out.println("++++++++++++++++");
67
        assertEquals(strValue, cache.get(cacheKey));
68
        System.out.println("-------------------");
69
    }
70
    
71
    public void testObjectJsonCache() throws Exception {
72
        // TODO Auto-generated method stub
73
        ICache cache = CacheFactory.getCache(cacheSingleName);
74
        IpuContextData contextData = new IpuContextData();
75
        contextData.put(cacheKey, strValue);
76
        cache.put(cacheContent, JSON.toJSONString((contextData)));
77
        String strContextData = cache.get(cacheContent).toString();
78
//        LOGGER.debug("strContextData===" + strContextData);
79
        System.out.println("strContextData===" + strContextData);
80
        IpuContextData2 contextData2 = JSON.parseObject(strContextData, IpuContextData2.class);
81
        System.out.println("contextData2.isDirty()===" + contextData2.isDirty());
82
//        LOGGER.debug("contextData2.isDirty()===" + contextData2.isDirty());
83
        assertEquals(strValue, contextData2.get(cacheKey));
84
    }
85
}

+ 111 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/RedisClusterTest.java

@ -0,0 +1,111 @@
1
package com.ai.ipu.cache.redis;
2
3
import java.io.IOException;
4
import java.util.HashSet;
5
import java.util.Set;
6
7
import junit.framework.TestCase;
8
import redis.clients.jedis.HostAndPort;
9
import redis.clients.jedis.JedisCluster;
10
import redis.clients.jedis.JedisPoolConfig;
11
12
import com.ai.ipu.basic.log.ILogger;
13
import com.ai.ipu.basic.log.IpuLoggerFactory;
14
import com.ai.ipu.cache.CacheFactory;
15
import com.ai.ipu.cache.CacheFactory.CacheType;
16
import com.ai.ipu.cache.ICache;
17
18
/**
19
 * @author huangbo@asiainfo.com
20
 * @team IPU
21
 * @date 2017年11月6日下午4:43:03
22
 * @desc Jedis原始包集群操作使用范例
23
 */
24
public class RedisClusterTest extends TestCase{
25
	private static final transient ILogger LOGGER = IpuLoggerFactory.createLogger(RedisClusterTest.class);
26
    private String[] hosts = {
27
                             "121.42.183.206",
28
                             "121.42.183.206",
29
                             "121.42.183.206",
30
                             "121.42.183.206",
31
                             "121.42.183.206",
32
                             "121.42.183.206"
33
                             };
34
    private int[] ports = {7101,7102,7103,7104,7105,7106};
35
    
36
    @Override
37
    protected void setUp() throws Exception {
38
        // TODO Auto-generated method stub
39
        super.setUp();
40
    }
41
    
42
    public void testCluster() throws Exception{
43
        JedisCluster jedisCluster = RedisCacheFactory.getJedisCluster("data");
44
        try {
45
            long start = System.currentTimeMillis();
46
            for (int i = 0; i < 100; i++) {
47
                @SuppressWarnings("unused")
48
                String result = jedisCluster.set("x" + i, "n" + i);
49
            }
50
            long end = System.currentTimeMillis();
51
            LOGGER.debug("普通同步调用方式耗时: " + ((end - start) / 1000.0) + "秒");
52
            jedisCluster.close();
53
        }catch (IOException e) {
54
        	LOGGER.error("IOException", e);
55
        }
56
    }
57
    
58
    public void testClusterWithAuth() throws Exception{
59
        JedisCluster jedisCluster = RedisCacheFactory.getJedisCluster("ssn");
60
        
61
        try {
62
            long start = System.currentTimeMillis();
63
            for (int i = 0; i < 100; i++) {
64
                jedisCluster.set("d" + i, "d" + i);
65
            }
66
            long end = System.currentTimeMillis();
67
            LOGGER.debug("普通同步调用方式耗时: " + ((end - start) / 1000.0) + "秒");
68
            jedisCluster.close();
69
        }catch (IOException e) {
70
        	LOGGER.error("IOException", e);
71
        }
72
    }
73
    
74
    public void testClusterPipelineWithAuth(){
75
        //GenericObjectPoolConfig的使用
76
        JedisPoolConfig config = new JedisPoolConfig();
77
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
78
        for(int i=0,len=hosts.length;i<len;i++){
79
            nodes.add(new HostAndPort(hosts[i], ports[i]));
80
        }
81
        JedisCluster jedisCluster = new JedisCluster(nodes, 5000, 5000, 3, "ipu",  config);
82
        try {
83
            long start = System.currentTimeMillis();
84
            for (int i = 0; i < 100; i++) {
85
                jedisCluster.set("b" + i, "b" + i);
86
            }
87
            long end = System.currentTimeMillis();
88
            LOGGER.debug("普通同步调用方式耗时: " + ((end - start) / 1000.0) + "秒");
89
            jedisCluster.close();
90
        }catch (IOException e) {
91
        	LOGGER.error("IOException", e);
92
        }
93
    }
94
    
95
    
96
    public void testCacheFactory()
97
    {
98
        try {
99
			ICache cache = CacheFactory.getCache(CacheType.redis, "jedisCluster");
100
			boolean result = cache.put("a", "a");
101
			
102
			LOGGER.debug(Boolean.toString(result));
103
			LOGGER.debug((String)cache.get("a"));
104
			LOGGER.debug(Boolean.toString(cache.remove("a")));
105
			LOGGER.debug(Boolean.toString(cache.remove("1")));
106
			
107
		} catch (Exception e) {
108
			LOGGER.error("IOException", e);
109
		}
110
    }
111
}

+ 225 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/RedisTest.java

@ -0,0 +1,225 @@
1
package com.ai.ipu.cache.redis;
2
3
import java.util.ArrayList;
4
import java.util.Arrays;
5
import java.util.List;
6
7
import com.ai.ipu.basic.log.ILogger;
8
import com.ai.ipu.basic.log.IpuLoggerFactory;
9
10
import junit.framework.TestCase;
11
import redis.clients.jedis.Jedis;
12
import redis.clients.jedis.JedisPoolConfig;
13
import redis.clients.jedis.JedisShardInfo;
14
import redis.clients.jedis.Pipeline;
15
import redis.clients.jedis.ShardedJedis;
16
import redis.clients.jedis.ShardedJedisPipeline;
17
import redis.clients.jedis.ShardedJedisPool;
18
import redis.clients.jedis.Transaction;
19
20
/**
21
 * @author huangbo@asiainfo.com
22
 * @team IPU
23
 * @date 2018年11月6日下午4:43:44
24
 * @desc Jedis原始包单服务操作使用范例
25
 */
26
public class RedisTest extends TestCase {
27
	private static final transient ILogger LOGGER = IpuLoggerFactory.createLogger(RedisTest.class);
28
	private Jedis jedis;
29
	private ShardedJedis shardedJedis;
30
	private String host;
31
	private int port;
32
	
33
	@Override
34
	protected void setUp() throws Exception {
35
		// TODO Auto-generated method stub
36
		super.setUp();
37
		host = "47.105.160.21";
38
		port = 7001;
39
	}
40
	
41
	/**
42
	 * 一、普通同步调用方式
43
	 */
44
	public void testNormal() {
45
		jedis = new Jedis(host, port);
46
		jedis.auth("ipu@321");
47
		long start = System.currentTimeMillis();
48
		List<Object> results = new ArrayList<Object>();
49
		for (int i = 0; i < 100; i++) {
50
			String result = jedis.set("n" + i, "n" + i);
51
			results.add(result);
52
		}
53
		LOGGER.debug("results.size()==="+results.size());
54
		long end = System.currentTimeMillis();
55
		LOGGER.debug("普通同步调用方式耗时: " + ((end - start) / 1000.0) + "秒");
56
		jedis.disconnect();
57
	}
58
	
59
	/**
60
	 * 二、事物调用方式
61
	 * discard()取消事务
62
	 */
63
	public void testTrans() { 
64
		jedis = new Jedis(host, port);
65
	    jedis.auth("Ipu@321!");
66
	    long start = System.currentTimeMillis(); 
67
	    Transaction tx = jedis.multi(); 
68
	    for (int i = 0; i < 10000; i++) { 
69
	        tx.set("t" + i, "t" + i); 
70
	    } 
71
	    List<Object> results = tx.exec();
72
	    LOGGER.debug("results.size()==="+results.size());
73
	    long end = System.currentTimeMillis(); 
74
	    LOGGER.debug("事物调用方式耗时: " + ((end - start)/1000.0) + " seconds");
75
	    jedis.disconnect(); 
76
	} 
77
78
	
79
	/**
80
	 * 三、管道调用方式
81
	 */
82
	public void testPipe() {
83
		// TODO Auto-generated method stub
84
		jedis = new Jedis(host, port);
85
	    jedis.auth("Ipu@321!");
86
	    Pipeline pipeline = jedis.pipelined(); 
87
	    long start = System.currentTimeMillis(); 
88
	    for (int i = 0; i < 10000; i++) { 
89
	        pipeline.set("p" + i, "p" + i); 
90
	    } 
91
	    List<Object> results = pipeline.syncAndReturnAll(); 
92
	    LOGGER.debug("results.size()==="+results.size());
93
	    long end = System.currentTimeMillis(); 
94
	    LOGGER.debug("管道调用方式耗时: " + ((end - start)/1000.0) + " seconds");
95
	    jedis.disconnect(); 
96
	}
97
	
98
	/**
99
	 * 四、管道事务调用方式
100
	 */
101
	public void testPipeTrans() {
102
		// TODO Auto-generated method stub
103
		jedis = new Jedis(host, port);
104
	    jedis.auth("ipu"); 
105
	    long start = System.currentTimeMillis(); 
106
	    Pipeline pipeline = jedis.pipelined(); 
107
	    pipeline.multi(); 
108
	    for (int i = 0; i < 10000; i++) { 
109
	        pipeline.set("" + i, "" + i); 
110
	    } 
111
	    pipeline.exec(); 
112
	    List<Object> results = pipeline.syncAndReturnAll();
113
	    LOGGER.debug("results.size()==="+results.size());
114
	    long end = System.currentTimeMillis(); 
115
	    LOGGER.debug("管道事务调用方式耗时: " + ((end - start)/1000.0) + " seconds"); 
116
	    jedis.disconnect(); 
117
	}
118
	
119
	/**
120
	 * 五、普通分布式调用方式
121
	 * 默认hash方式存储
122
	 */
123
	public void testShardNormal() {
124
		// TODO Auto-generated method stub
125
		List<JedisShardInfo> distribut = Arrays.asList( 
126
	            new JedisShardInfo(host,6379), 
127
	            new JedisShardInfo(host,6380)); 
128
129
	    shardedJedis = new ShardedJedis(distribut);
130
	    List<Object> results = new ArrayList<Object>();
131
	    long start = System.currentTimeMillis(); 
132
	    for (int i = 0; i < 100000; i++) { 
133
	        String result = shardedJedis.set("sn" + i, "n" + i);
134
	        results.add(result);
135
	    }
136
	    LOGGER.debug("results.size()==="+results.size());
137
	    long end = System.currentTimeMillis(); 
138
	    LOGGER.debug("普通分布式调用方式耗时: " + ((end - start)/1000.0) + " seconds"); 
139
140
	    shardedJedis.disconnect(); 
141
	}
142
	
143
	/**
144
	 * 六、管道分布式调用方式
145
	 */
146
    public void testShardPipe() {
147
        // TODO Auto-generated method stub
148
        List<JedisShardInfo> shards = Arrays.asList(new JedisShardInfo(host, 6379), 
149
                new JedisShardInfo(host, 6380));
150
151
        shardedJedis = new ShardedJedis(shards);
152
        ShardedJedisPipeline pipeline = shardedJedis.pipelined();
153
        long start = System.currentTimeMillis();
154
        for (int i = 0; i < 100000; i++) {
155
            pipeline.set("sp" + i, "p" + i);
156
        }
157
        List<Object> results = pipeline.syncAndReturnAll();
158
        LOGGER.debug("results.size()===" + results.size());
159
        long end = System.currentTimeMillis();
160
        LOGGER.debug("Pipelined@Sharing SET: " + ((end - start) / 1000.0) + " seconds");
161
162
        shardedJedis.disconnect();
163
    }
164
	
165
	/**
166
	 * 七、分布式连接池同步调用方式
167
	 */
168
	public void testShardPool() {
169
		// TODO Auto-generated method stub
170
		List<JedisShardInfo> shards = Arrays.asList(
171
				new JedisShardInfo(host, 6379), 
172
				new JedisShardInfo(host, 6380));
173
		ShardedJedisPool pool = new ShardedJedisPool(new JedisPoolConfig(), shards);
174
		shardedJedis = pool.getResource();
175
176
		List<Object> results = new ArrayList<Object>();
177
		long start = System.currentTimeMillis();
178
		for (int i = 0; i < 100000; i++) {
179
			String result = shardedJedis.set("spn" + i, "n" + i);
180
			results.add(result);
181
		}
182
		
183
		LOGGER.debug("results.size()===" + results.size());
184
		long end = System.currentTimeMillis();
185
		pool.returnResource(shardedJedis);
186
		LOGGER.debug("Simple@Pool SET: " + ((end - start) / 1000.0) + " seconds");
187
188
		pool.destroy();
189
	}
190
	
191
	/**
192
	 * 八、分布式连接池异步调用方式
193
	 */
194
	public void testShardPipePool() {
195
		// TODO Auto-generated method stub
196
		List<JedisShardInfo> shards = Arrays.asList( 
197
	            new JedisShardInfo("localhost",6379), 
198
	            new JedisShardInfo("localhost",6380)); 
199
200
	    ShardedJedisPool pool = new ShardedJedisPool(new JedisPoolConfig(), shards); 
201
	    shardedJedis = pool.getResource(); 
202
	    ShardedJedisPipeline pipeline = shardedJedis.pipelined(); 
203
204
	    long start = System.currentTimeMillis(); 
205
	    for (int i = 0; i < 100000; i++) { 
206
	        pipeline.set("sppn" + i, "n" + i); 
207
	    } 
208
	    List<Object> results = pipeline.syncAndReturnAll();
209
	    LOGGER.debug("results.size()===" + results.size());
210
	    long end = System.currentTimeMillis(); 
211
	    pool.returnResource(shardedJedis); 
212
	    LOGGER.debug("Pipelined@Pool SET: " + ((end - start)/1000.0) + " seconds"); 
213
	    pool.destroy(); 
214
	}
215
	
216
	public void testGet() {
217
        jedis = new Jedis(host, port);
218
        long start = System.currentTimeMillis();
219
        jedis.keys("*");
220
        String result = jedis.get("msg");
221
        LOGGER.debug("返回结果:"+result);
222
        LOGGER.debug("普通同步调用方式耗时: " + (System.currentTimeMillis() - start) + "ms");
223
        jedis.disconnect();
224
    }
225
}

+ 53 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/context/IpuContextData.java

@ -0,0 +1,53 @@
1
package com.ai.ipu.cache.redis.context;
2
3
import java.io.Serializable;
4
import java.util.HashMap;
5
import java.util.Map;
6
7
/**
8
 * @author huangbo@asiainfo.com
9
 * @team IPU
10
 * @date 2018年11月6日下午7:54:04
11
 * @desc 上下文数据对象设计
12
 * 1.不使用java对象:单点登录时,java对象的包路径需要一致。不太合理。
13
 * 2.不继承HashMap:继承的话,Json转换时会丢失私有属性dirty。dirty和xxxxDirty均被识别成dirty
14
 */
15
public class IpuContextData implements Serializable{
16
    private static final long serialVersionUID = 183972639715505942L;
17
    private Map<String, String> data;
18
    private boolean isDirty;
19
20
	public IpuContextData() {
21
	    data = new HashMap<String, String>();
22
	}
23
	
24
	public Map<String, String> getData() {
25
		// TODO Auto-generated method stub
26
		return data;
27
	}
28
29
	public void setData(Map<String, String> data) {
30
		// TODO Auto-generated method stub
31
		this.data = data;
32
		setDirty(true);
33
	}
34
	
35
	public void put(String key, String value){
36
	    data.put(key, value);
37
		setDirty(true);
38
	}
39
	
40
	public String get(String key){
41
		return data.get(key);
42
	}
43
44
	public boolean isDirty() {
45
		// TODO Auto-generated method stub
46
		return isDirty;
47
	}
48
	
49
	public void setDirty(boolean isDirty) {
50
		// TODO Auto-generated method stub
51
		this.isDirty = isDirty;
52
	}
53
}

+ 48 - 0
ipu-redis-example/src/test/java/com/ai/ipu/cache/redis/context/IpuContextData2.java

@ -0,0 +1,48 @@
1
package com.ai.ipu.cache.redis.context;
2
3
import java.io.Serializable;
4
import java.util.HashMap;
5
import java.util.Map;
6
7
/**
8
 * 上下文数据,存储的时候会被序列化
9
 */
10
public class IpuContextData2 implements Serializable{
11
    private static final long serialVersionUID = 183972639715505942L;
12
    private Map<String, String> data;
13
    private boolean isDirty;
14
15
    public IpuContextData2() {
16
        data = new HashMap<String, String>();
17
    }
18
    
19
    public Map<String, String> getData() {
20
        // TODO Auto-generated method stub
21
        return data;
22
    }
23
24
    public void setData(Map<String, String> data) {
25
        // TODO Auto-generated method stub
26
        this.data = data;
27
        setDirty(true);
28
    }
29
    
30
    public void put(String key, String value){
31
        data.put(key, value);
32
        setDirty(true);
33
    }
34
    
35
    public String get(String key){
36
        return data.get(key);
37
    }
38
39
    public boolean isDirty() {
40
        // TODO Auto-generated method stub
41
        return isDirty;
42
    }
43
    
44
    public void setDirty(boolean isDirty) {
45
        // TODO Auto-generated method stub
46
        this.isDirty = isDirty;
47
    }
48
}

+ 47 - 0
ipu-redis-example/src/test/reources/ipu-cache.xml

@ -0,0 +1,47 @@
1
<?xml version = '1.0' encoding = 'UTF-8'?>
2
<caches>
3
	<!-- ====================redis缓存============================ -->
4
	<cache name="ssn" type="redis">
5
		<servers>
6
	        <!-- 如果不是cluster,则只使用第一个redis -->
7
	        <server ip="47.105.160.21" port="7001" />
8
	        <server ip="47.105.160.21" port="7002" />
9
	        <server ip="47.105.160.21" port="7003" />
10
	        <server ip="121.42.183.206" port="7104" />
11
	        <server ip="121.42.183.206" port="7105" />
12
	        <server ip="121.42.183.206" port="7106" />
13
	    </servers>
14
		<!-- 客户端类型:Jedis,JedisCluster -->
15
	    <config name="clientType" value="JedisCluster"/>
16
	    <!-- 访问redis的密码,可以为空 -->
17
	    <config name="auth" value="ipu@321"/>
18
	    <!-- redis池的可用连接实例的最大数目,缺省为8 -->
19
	    <config name="poolSize" value="10"/>
20
	    <!-- redis池最多有多少个状态为idle(空闲的)的jedis实例,缺省为8,空闲连接大于这个数会进行回收 -->
21
	    <config name="maxIdle"/>
22
	    <!-- 最小空闲数,空闲连接小于这个数会建立新的连接,缺省为0 -->
23
	    <config name="minIdle"/>
24
	    <!-- 等待Response超时时间,默认5000ms -->
25
	    <config name="soTimeout"/>
26
	    <!-- 连接Redis Server超时时间,默认5000ms -->
27
	    <config name="connTimeout"/>
28
	    <!-- 出现异常最大重试次数 -->
29
	    <config name="maxAttempts"/>
30
	</cache>
31
	
32
	<cache name="data" type="redis">
33
		<servers>
34
	        <!-- 如果不是cluster,则只使用第一个redis -->
35
	        <server ip="47.105.160.21" port="7001" />
36
	    </servers>
37
	    <config name="auth" value="ipu@321"/>
38
	</cache>
39
	<cache name="single" type="redis">
40
		<servers>
41
	        <!-- 如果不是cluster,则只使用第一个redis -->
42
	        <server ip="47.105.160.21" port="7101" />
43
	    </servers>
44
	    <config name="auth" value="ipu@321"/>
45
	</cache>
46
	<!-- ================================================ -->
47
</caches>

+ 12 - 0
ipu-redis-example/src/test/reources/memcache.xml

@ -0,0 +1,12 @@
1
<?xml version = '1.0' encoding = 'UTF-8'?>
2
3
<memcache>
4
	<default-datacenter>center1</default-datacenter>
5
	<datacenter name="center1">
6
		<cluster name="wade_cache">
7
			<heartbeat-second>5</heartbeat-second>
8
			<pool-size>2</pool-size>
9
			<address master="47.105.160.21:11211" />
10
		</cluster>
11
	</datacenter>
12
</memcache>