> 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>

更新jar包 · 32ccee68f4 - Nuosi Git Service
Browse Source

更新jar包

liutong3 5 years ago
parent
commit
32ccee68f4
1 changed files with 0 additions and 0 deletions
  1. BIN
      ipu-db-example/libs/ipu-sql-mgmt-3.2-SNAPSHOT.jar

BIN
ipu-db-example/libs/ipu-sql-mgmt-3.2-SNAPSHOT.jar