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系统对 ...
随机推荐
- 技术领导(Technical Leader)画像
程序员都讨厌被管理,而乐于被领导.管理的角色由PM(project manager)扮演,具体来说,PM负责提需求.改改改.大多数情况,PM是不懂技术的,这也是程序员觉得PM难以沟通的原因.而后者由技 ...
- HDU1251统计难题(水字典树)
统计难题 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others) Total Subm ...
- WPF 验证没有通过无法保存数据(非常好)+ 虚似数据库
Validation control with a single validation rule is easy, but what if we need to validate a control ...
- 提纲挈领webrtc之NS(noise suppression)模块
Noise suppression,就是大家说的降噪.这种降噪是把人声和非人声区分开来,把非人声当成噪声. 一段包含人声和噪声的音频经过该模块处理,从理论上讲,只剩下人声了. webrtc的NS在业内 ...
- win10 UWP 剪贴板 Clipboard
win10 UWP 剪贴板 Clipboard使用Windows.ApplicationModel.DataTransfer.Clipboard 设置文本 DataPackage dataPackag ...
- React与Preact差异之 -- setState
Preact是React的轻量级实现,是React比较好的替代者之一,有着体积小的优点,当然与React之间一定会存在实现上的差异,本文介绍了在 setState 方面的差异之处. 源码分析 首先来分 ...
- Spring 组成
Spring 主要由 Bean Context Core 三个组件组成 Bean 组件是整个 Spring 核心,Spring 通过管理 Bean 组件提供服务 Context 是 Bean 组件容器 ...
- 如何通过写bat 安装Windows服务,本人亲测成功
1. 安装的bat文件 @echo on color 2f mode con: cols=80 lines=25 @echo 请按任意键开始安装后台服务... pause cd /d %~dp0 Le ...
- windows平台安装并使用MongoDB
下载并安装MongoDB,我的安装路径:D:\Program_Files\MongoDB 创建数据库目录,我的目录:D:\mongodb\data\db 命令行下运行MongoDB服务器: 在命令行窗 ...
- phalcon——调度控制器
将侦听者绑定到组件上: use Phalcon\Mvc\Dispatcher as MvcDispatcher, Phalcon\Events\Manager as EventsManager; $d ...