Java中的Redis应用
1、配置redis集群
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?xml version= "1.0" encoding= "UTF-8" ?> <redisCluster> <!--userRoute --> <clusterGroup name= "userRoute" selectdb= "1" > <server host= "10.177.129.16" port= "6379" ></server> <server host= "10.177.129.15" port= "6379" ></server> </clusterGroup> <!--sessionRoute --> <clusterGroup name= "sessionRoute" selectdb= "2" > <server host= "10.177.129.16" port= "6379" ></server> <server host= "10.177.129.15" port= "6379" ></server> </clusterGroup> <!--publicData --> <clusterGroup name= "publicData" > <server host= "10.177.129.16" port= "6379" ></server> <server host= "10.177.129.15" port= "6379" ></server> </clusterGroup> </redisCluster> |
2、创建redis连接属性实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package net.itxm.cms.syscore.pojo; /** * redis连接属性 * */ public class RedisCluster { private String selectdb; private String hostIp; private String port; public String getSelectdb() { return selectdb; } public void setSelectdb(String selectdb) { this .selectdb = selectdb; } public String getHostIp() { return hostIp; } public void setHostIp(String hostIp) { this .hostIp = hostIp; } public String getPort() { return port; } public void setPort(String port) { this .port = port; } } |
3、解析redis集群配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
package net.itxm.itreasury.test.jedis; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; /** * 解析redis集群配置 * */ public class RedisConfig { public static Map<String,List<RedisCluster>> redisGroupMap = null ; //有参构造函数 public RedisConfig() { } //获取所有clusterGroup组的键值对 public static Map<String,List<RedisCluster>> getRedisGroupMap(){ //读取xml文件 Document document=readXmlFile(); //获得clusterGroup节点的key 和 list if (redisGroupMap == null ) { redisGroupMap=getMapByItemsGroup(document); } return redisGroupMap; } //读取redisConfig配置文件 private static Document readXmlFile(){ //创建读入对象 SAXReader reader = new SAXReader(); //创建document实例 Document doc= null ; try { //从类路径下加载文件redisConfig.xml Resource resource = new ClassPathResource( "redisClusterConfig.xml" ); //指定文件资源对应的编码格式(UTF-8),这样才能正确读取文件的内容,而不会出现乱码 EncodedResource encodeResource = new EncodedResource(resource, "UTF-8" ); doc = reader.read(encodeResource.getReader()); } catch (IOException e) { System.out.println( "无法读取系统配置文件redisConfig.xml,可能该文件不存在" ); } catch (DocumentException e) { System.out.println( "解析redisConfig.xml文件出现异常" ); } return doc; } //读取xml节点,返回节点为redisGroup的Map private static Map<String,List<RedisCluster>> getMapByItemsGroup(Document document){ Map<String,List<RedisCluster>> itemmap= new HashMap<String,List<RedisCluster>>(); try { //获得根节点 Element root=document.getRootElement(); //获得根节点下所有子节点clusterGroup的list List itemsList=root.selectNodes( "./clusterGroup" ); for ( int i= 0 ;i<itemsList.size();i++){ //获得节点Items Element items=(Element)itemsList.get(i); String groupName=items.attribute( "name" ).getText(); String selectdb = items.attribute( "selectdb" )== null ? "" :items.attribute( "selectdb" ).getText(); // if(groupName!=null&&groupName.equals(this.getGroupName())){ //获得clusterGroup下所有子节点service的list List itemList=items.elements(); //获得service节点的值 List<RedisCluster> redisClusterList = getItemList(itemList,selectdb); itemmap.put(groupName, redisClusterList); // } } } catch (Exception e){ } return itemmap; } //获得所有Item下节点的redis服务节点 private static List<RedisCluster> getItemList(List itemList,String selectdb){ List<RedisCluster> redisClusterList = new ArrayList<RedisCluster>(); for ( int i= 0 ;i<itemList.size();i++){ //获得节点server Element item=(Element)itemList.get(i); String hostIp = item.attribute( "host" ).getText(); String port = item.attribute( "port" ).getText(); RedisCluster redisCluster = new RedisCluster(); redisCluster.setHostIp(hostIp); redisCluster.setPort(port); redisCluster.setSelectdb(selectdb); redisClusterList.add(redisCluster); } return redisClusterList; } public static void main(String[] args) { getRedisGroupMap(); //JedisUtil.insertPublicDataObject("user1", "张三", JedisUtil.ONLINE_USER); //JedisUtil.insertPublicDataObject("user2", "李四", JedisUtil.ONLINE_USER); //JedisUtil.insertPublicDataObject("user3", "王五", JedisUtil.ONLINE_USER); Set s = JedisUtil.getAllSet(JedisUtil.ONLINE_USER); Iterator it = s.iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = JedisUtil.getString(key,JedisUtil.ONLINE_USER); System.out.println(key + value); } String test = JedisUtil.getString( "user1" ,JedisUtil.ONLINE_USER); System.out.println(test); } } |
4、操作redis数据库的工具类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
|
package net.itxm.cms.syscore.utils; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import java.util.zip.CRC32; import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.JedisConnectionException; import com.google.gson.Gson; import com.isoftstone.cms.syscore.pojo.RedisCluster; public class JedisUtil { // 数据库 public static final String STORE_LOGINUSER = "4" ; // 商户登陆用户 public static final String STORE_INFO = "5" ; // 商户状态 商户购买服务有效期 public static final String CHECK_CODE = "6" ; // 验证码 public static final String MENU = "7" ; // 全部菜单 public static final String SERVICE = "8" ; // 服务收费信息 public static final String STORE_LOGINKEY = "9" ; // 初始化登录公钥 私钥对 // 固定key public static final String ALL_MENU_KEY = "ALL_MENU_KEY" ; public static final String BUY_SERVICE_KEY = "BUY_SERVICE_KEY" ; // 服务收费购买key public static final String ALL_SERVICE_KEY = "ALL_SERVICE_KEY" ; //所有服务 public static final String MENU_AUTHORITY = "MENU_AUTHORITY" ; // 菜单权限 public static final String STORE_MENU_KEY = "STORE_MENU_KEY" ; // 需要商户分配的业务菜单 public static final String STORE_SERVICE_KEY = "STORE_SERVICE_KEY" ; // 商户收费key public static final String SYSTE_MENU_KEY = "SYSTE_MENU_KEY" ; // 系统管理菜单key // jedis服务组业务类型 public static final String CONT_CLUSTERNAME_PUBLICDATA = "publicData" ; public static final String CONT_CLUSTERNAME_SESSIONROUTE = "sessionRoute" ; public static final String CONT_CLUSTERNAME_USERROUTE = "userRoute" ; // 操作方式 0 插入 1获取 2 删除 public static final long INSERT_OPERATION = 0 ; public static final long GET_OPERATION = 1 ; public static final long DELETE_OPERATION = 2 ; // 验证码过期秒数 public static final int CHECKCODE_EXPIRESECONDS = 5 * 60 ; // session过期秒数 public static final int EXPIRESECONDS = 30 * 60 ; private static void closeJedis(Jedis jedis) { try { jedis.quit(); } catch (JedisConnectionException e) { e.printStackTrace(); } jedis.disconnect(); } /** * 根据Key获取字符串 * * @param key * @param jedisGroup */ public static String getString(String key, String selectdb) { Jedis jedis = getPublicDataJedis(key, GET_OPERATION, selectdb); return jedis.get(key); } /** * 获取所有数据set * @param selectdb * @return */ public static Set getAllSet(String selectdb) { Jedis jedis = getDataJedis(GET_OPERATION, selectdb); return jedis.keys( "*" ); } /** * 默认取配置文件的第一个数据库 * @param operation * @param selectdb * @return */ private static Jedis getDataJedis( long operation, String selectdb) { if (RedisConfig.redisGroupMap == null ) { RedisConfig.redisGroupMap = RedisConfig.getRedisGroupMap(); } List<RedisCluster> clustersList = RedisConfig.redisGroupMap.get(CONT_CLUSTERNAME_PUBLICDATA); int clusterNo = 0 ; //默认存到第一个 RedisCluster cluster = clustersList.get(clusterNo); Jedis jedis = new Jedis(cluster.getHostIp(), Integer.valueOf(cluster.getPort())); jedis.select(Integer.valueOf(selectdb)); return jedis; } /** * 删除数据 * * @param key * @param jedisGroup */ public static void deleteObject(String key, String jedisGroup) { Jedis jedis = getJedis(key, jedisGroup, DELETE_OPERATION); jedis.del(key); closeJedis(jedis); } /** * 删除公共数据 * * @param key * @param objClass * @param selectdb */ public static void deletePublicDataObject(String key, String selectdb) { Jedis jedis = getPublicDataJedis(key, DELETE_OPERATION, selectdb); jedis.del(key); closeJedis(jedis); } /** * 获取jedis的库实例 * * @param key * @param jedisGroup * @param operation * @return */ private static Jedis getJedis(String key, String jedisGroup, long operation) { if (RedisConfig.redisGroupMap == null ) { RedisConfig.redisGroupMap = RedisConfig.getRedisGroupMap(); } List<RedisCluster> clustersList = RedisConfig.redisGroupMap.get(jedisGroup); int arrayLength = clustersList.size(); // 根据key值算出该信息应该存入到那个 int clusterNo = getRedisNo(key, arrayLength); RedisCluster cluster = clustersList.get(clusterNo); Jedis jedis = new Jedis(cluster.getHostIp(), Integer.valueOf(cluster.getPort())); jedis.select(Integer.valueOf(cluster.getSelectdb())); return jedis; } /** * redis key值获取对象 * * @param key * @param objClass * @param jedisGroup * @return */ public static Object getObject(String key, Class objClass, String jedisGroup) { Jedis jedis = getJedis(key, jedisGroup, GET_OPERATION); String sObj = jedis.get(key); closeJedis(jedis); Gson gson = new Gson(); return gson.fromJson(sObj, objClass); } /** * 获取公共数据jedis的库实例 * * @param key * @param jedisGroup * @param operation * @return */ private static Jedis getPublicDataJedis(String key, long operation, String selectdb) { if (RedisConfig.redisGroupMap == null ) { RedisConfig.redisGroupMap = RedisConfig.getRedisGroupMap(); } List<RedisCluster> clustersList = RedisConfig.redisGroupMap.get(CONT_CLUSTERNAME_PUBLICDATA); int arrayLength = clustersList.size(); // 根据key值算出该信息应该存入到那个 int clusterNo = getRedisNo(key, arrayLength); <a href= "http://www.itxm.net/" target= "_blank" >RedisCluster </a>cluster = clustersList.get(clusterNo); Jedis jedis = new Jedis(cluster.getHostIp(), Integer.valueOf(cluster.getPort())); jedis.select(Integer.valueOf(selectdb)); return jedis; } /** * publicdata redis key值获取对象 * * @param key * @param objClass * @param jedisGroup * @return */ public static Object getPublicDataObject(String key, Class objClass, String selectdb) { Jedis jedis = getPublicDataJedis(key, GET_OPERATION, selectdb); String sObj = jedis.get(key); closeJedis(jedis); Gson gson = new Gson(); return gson.fromJson(sObj, objClass); } /** * publicdata redis key值获取对象 List<Entity> * * @param key * @param objClass * @param jedisGroup * @return */ public static Object getPublicDataObjectByType(String key, Type type, String selectdb) { Jedis jedis = getPublicDataJedis(key, GET_OPERATION, selectdb); String sObj = jedis.get(key); closeJedis(jedis); Gson gson = new Gson(); return gson.fromJson(sObj, type); } /** * 获取redis服务器库编号 * * @param hashKey * @return */ public static int getRedisNo(String key, int arraySize) { long hashKey = hash(key); int redisNo = ( int ) (hashKey % arraySize); return redisNo; } /** * 根据key值算出hash值 * * @param k * @return */ public static long hash(String k) { CRC32 crc32 = new CRC32(); crc32.update(k.getBytes()); return crc32.getValue(); } /** * redis 根据key值将对象插入到不同的库中 * * @param key * @param insertObj * @param jedisGroup */ public static void insertObject(String key, Object insertObj, String jedisGroup) { Jedis jedis = getJedis(key, jedisGroup, INSERT_OPERATION); Gson gson = new Gson(); jedis.set(key, gson.toJson(insertObj)); closeJedis(jedis); } /** * redis 根据key值将对象插入到不同的库中 * * @param key * @param insertObj * @param jedisGroup * @param expire */ public static void insertObject(String key, Object insertObj, String jedisGroup, int expireSeconds) { Jedis jedis = getJedis(key, jedisGroup, INSERT_OPERATION); Gson gson = new Gson(); jedis.setex(key, expireSeconds, gson.toJson(insertObj)); closeJedis(jedis); } /** * publicdata redis 根据key值将对象插入到不同的库中 * * @param key * @param insertObj * @param jedisGroup */ public static void insertPublicDataObject(<a href= "http://www.itxm.net/" target= "_blank" >String </a>key, Object insertObj, String selectdb) { Jedis jedis = getPublicDataJedis(key, INSERT_OPERATION, selectdb); Gson gson = new Gson(); jedis.set(key, gson.toJson(insertObj)); closeJedis(jedis); } /** * publicdata redis 根据key值将对象插入到不同的库中, * * @param key * @param insertObj * @param jedisGroup * @param expireSeconds */ public static void insertPublicDataObject(String key, Object insertObj, String selectdb, int expireSeconds) { Jedis jedis = getPublicDataJedis(key, INSERT_OPERATION, selectdb); Gson gson = new Gson(); jedis.setex(key, expireSeconds, gson.toJson(insertObj)); closeJedis(jedis); } /** * 更新redis中key的超时时间 * * @param key * @param jedisGroup * @param expireSeconds */ public static void resetExpireSeconds(String key, String jedisGroup, int expireSeconds) { Jedis jedis = getJedis(key, jedisGroup, GET_OPERATION); jedis.expire(key, expireSeconds); closeJedis(jedis); } } |
5、所需jar包
Java中的Redis应用的更多相关文章
- 在java中使用redis
在java中使用redis很简单,只需要添加jedist.jar,通过它的api就可以了.而且,api和redis的语法几乎完全相同.以下简单的测试: 参考:http://www.runoob.com ...
- JAVA中使用Redis
上节讲解了如何在centos上安装redis,点击查看.本节我们学习在java中使用redis.需要将jedis-*.jar添加到classpath(点击下载),如果使用连接池还需要commons-p ...
- Redis入门教程(三)— Java中操作Redis
在Redis的官网上,我们可以看到Redis的Java客户端众多 其中,Jedis是Redis官方推荐,也是使用用户最多的Java客户端. 开始前的准备 使用jedis使用到的jedis-2.1.0. ...
- Redis笔记(六):Java中使用Redis
Java程序使用Redis 添加依赖包 Maven依赖方式 <dependency> <groupId>redis.clients</groupId> <ar ...
- java中使用redis --- Hash的简单应用
1.java代码 public class RedisTest01 { public static void main(String[] args) { // connect redis server ...
- Java中的Redis 哨兵高可用性
让我们探索Redis Sentinel,看看如何在Java上运行它,一起来看看,最近get了很多新知识,分享给大家参考学习.需要详细的java架构思维导图路线也可以评论获取! 什么是Redis哨兵? ...
- java中使用 redis (转载)
jedis是一个著名的key-value存储系统,而作为其官方推荐的java版客户端jedis也非常强大和稳定,支持事务.管道及有jedis自身实现的分布式. 在这里对jedis关于事务.管道和分布式 ...
- Redis(2)用jedis实现在java中使用redis
昨天已经在windows环境下安装使用了redis. 下面准备在java项目中测试使用redis. redis官网推荐使用jedis来访问redis.所以首先准备了jedis的jar包,以及需要依赖的 ...
- Java中操作Redis
一.server端安装 1.下载 https://github.com/MSOpenTech/redis 可看到当前可下载版本:redis2.6 下载后的文件为: 解压后,选择当前64位win7系统对 ...
随机推荐
- pgpool-II主备流复制的架设
1.环境 OS: CentOS release 6.4 (Final) DB: postgresql 9.3.6 pgpool服务器: pgpool 172.16.0.240 数据库主服务器:mast ...
- jvm系列(十):如何优化Java GC「译」
本文由CrowHawk翻译,是Java GC调优的经典佳作. 本文翻译自Sangmin Lee发表在Cubrid上的"Become a Java GC Expert"系列文章的第三 ...
- Nunit测试工具使用实例
前言: 本文主要是介绍了Nunit的基本使用,其中参详了很多已有的文章,由于最近要使用其进行测试,所以对网上的文章做了下整理,同时加入了一些自己的实践. NUnit的属性 TestFixture 它标 ...
- Python系列之模块、和字符串格式化
Python 模块 模块让你能够有逻辑地组织你的Python代码段. 把相关的代码分配到一个 模块里能让你的代码更好用,更易懂. 模块也是Python对象,具有随机的名字属性用来绑定或引用. 模块分为 ...
- spring cloud+dotnet core搭建微服务架构:配置中心(四)
前言 我们项目中有很多需要配置的地方,最常见的就是各种服务URL地址,这些地址针对不同的运行环境还不一样,不管和打包还是部署都麻烦,需要非常的小心.一般配置都是存储到配置文件里面,不管多小的配置变动, ...
- jS判断浏览器终端
在做移动端项目的时候,常常会遇到需要判断页面浏览终端的需求.要想判断是什么浏览器终端,先打印 navigator.userAgent 出来.所以收集了几种比较常用的方法: if(/(iPhone|iP ...
- 关于Websockets问题:
Websockets是一种与服务器进行全双工,双向通信的信道,它不使用http协议,他有自己的协议即自定义协议,ws协议:它的安全协议为wss协议.这种协议专门为快速传输小数据而设计的.对服务其有一 ...
- 在C#中实现串口通信的方法
通常,在C#中实现串口通信,我们有四种方法: 第一:通过MSCOMM控件这是最简单的,最方便的方法.可功能上很难做到控制自如,同时这个控件并不是系统本身所带,所以还得注册,不在本文讨论范围.可以访问h ...
- DevOps之基础设施
唠叨话 关于德语关我屁事的知识点,仅提供精华汇总,具体知识点细节,参考教程网址,如需帮助,请留言. <信息技术(IT )> 关于IT信息技术的基础设施,知识与技能的层次(知道.理解.运用) ...
- cocos2dx - 控件扩展之pageview循环显示
接上一节内容:cocos2dx - shader实现任意动画的残影效果 本节主要讲一下扩展PageView控件功能 在实际游戏应用中,经常会碰到用原来的控件难以实现的功能.这时候就需要根据需求,通过选 ...