s="lines-num lines-num-old"> 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
}

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

@ -1,182 +0,0 @@
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
}

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

@ -1,305 +0,0 @@
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
}

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

@ -1,300 +0,0 @@
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
}

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

@ -1,15 +0,0 @@
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
}

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

@ -1,33 +0,0 @@
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
}

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

@ -1,67 +0,0 @@
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
}

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

@ -1,46 +0,0 @@
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
}

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

@ -1,24 +0,0 @@
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
}

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

@ -1,69 +0,0 @@
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
}

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

@ -1,41 +0,0 @@
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
}

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

@ -1,85 +0,0 @@
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
}

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

@ -1,111 +0,0 @@
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
}

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

@ -1,225 +0,0 @@
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
}

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

@ -1,53 +0,0 @@
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
}

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

@ -1,48 +0,0 @@
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
}

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

@ -1,47 +0,0 @@
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>

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

@ -1,12 +0,0 @@
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>

android-share - Nuosi Git Service

ipu的trunk版的android工程和服务端工程。

chengwb3 381dc7f09d 集群推送消息第一版提交 8 年之前
..
.gitignore 61ff9d2503 Merge branch 'master' of 9 年之前
web.xml 381dc7f09d 集群推送消息第一版提交 8 年之前