0%

JAVA连接REDIS缓存数据库

3.2.1 导入JAR包

commons-pool2-2.3.jar
jedis-2.7.0.jar

3.2.2 单实例连接
代码:

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
package com.itheima.redis;


import redis.clients.jedis.Jedis;



/**

* 演示Jedis对象操作Redis内存数据库

* 相当于客户端

*/

public class Demo01 {

public static void main(String[] args) {

//NO1)创建Jedis对象

//参数一: 连接装Redis数据库的机器的IP

//参数二:Redis数据库占用的端口号

Jedis jedis = new Jedis(“127.0.0.1”,6379);

//NO2)调用Jedis对象的API操作Redis数据库

//选择15号数据库

jedis.select(15);

//将key=value存入15号数据库

jedis.set(“username”,“赵君”);

//取出key=value

System.out.println(jedis.get(“username”));

//NO3关闭Jedis对象

jedis.close();

}

}



package com.itheima.redis;



import java.util.List;

import redis.clients.jedis.Jedis;



/**

* 演示Jedis对象操作Redis内存数据库

* 相当于客户端

*/

public class Demo02 {

public static void main(String[] args) {

//NO1)创建Jedis对象

Jedis jedis = new Jedis(“127.0.0.1”,6379);

//NO2)调用Jedis对象的API操作Redis数据库,默认选择0号数据库

jedis.select(15);

jedis.lpush(“class”,new String[]{“如茶”,“如草”,“如叶”,“如花”});

List<String> list = jedis.lrange(“class”,0,-1);

for(String str : list){

System.out.print(str + ” “);

}

//NO3关闭Jedis对象

jedis.close();

}

}

3.2.3 连接池连接
代码:

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
package com.itheima.redis;


import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;



/**

* 演示Jedis连接池

* 客户端

*/

public class Demo01 {

public static void main(String[] args) {

//NO1)创建Jedis连接池配置对象,类似到c3p0-config.xml文件

JedisPoolConfig config = new JedisPoolConfig();

//NO2)创建Jedis连接池

//设置连接池最多存入10个Jedis对象

config.setMaxTotal(10);

//从连接池中取出Jedis对象最多等2秒

config.setMaxWaitMillis(2000);

//NO3)从Jedis连接池中取出一个Jedis对象

JedisPool pool = new JedisPool(config,“127.0.0.1”,6379);

//NO4)使用Jedis对象操作Redis数据库

Jedis jedis = pool.getResource();

//选择15号数据库

jedis.select(15);

//根据key找value

String username = jedis.get(“username”);

//如果value找到了

if(username != null){

//删除该key

jedis.del(“username”);

}

//NO5)将Jedis对象还回给Jedis连接池

jedis.close();

}

}

3.2.4 编写JedisUtil工具类
代码:

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
package com.itheima.redis.service;


import redis.clients.jedis.Jedis;

import com.itheima.redis.util.JedisUtil;



/**

* 演示通过JedisUtils来获取,操作,关闭Jedis对象

* 客户端

*/

public class Demo01 {

public static void main(String[] args) throws Exception{

//获取Jedis对象

Jedis jedis = JedisUtil.getJedis();

//使用Jedis对象操作Redis数据库

jedis.set(“address”,“长沙”);

//关闭Jedis对象

JedisUtil.close(jedis);

}

}



package com.itheima.redis.util;



import java.util.ResourceBundle;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;



/**

* Jedis工具类

*/

public final class JedisUtil {

private static JedisPool pool;

private static String maxTotal;

private static String maxWaitMillis;

private static String host;

private static String port;

/**

* 读取src/jedis.properties属性文件中的内容

*/

static{

//ResourceBundle专用于去类路径下找*.properties文件,所以扩展名properties可以不写

//建议项目中的配置文件放在src目录下

ResourceBundle rb = ResourceBundle.getBundle(“jedis”);

//根据key找value

maxTotal = rb.getString(“maxTotal”);

maxWaitMillis = rb.getString(“maxWaitMillis”);

host = rb.getString(“host”);

port = rb.getString(“port”);

}

/**

* 创建连接池对象

*/

static{

JedisPoolConfig config = new JedisPoolConfig();

config.setMaxTotal(Integer.parseInt(maxTotal));

config.setMaxWaitMillis(Integer.parseInt(maxWaitMillis));

pool = new JedisPool(config,host,Integer.parseInt(port));

}

private JedisUtil(){

}

/**

* 获取Jedis对象

*/

public static Jedis getJedis() throws Exception{

//如果连接池非空

if(pool != null){

//从连接池中获取Jedis对象

return pool.getResource();

}else{

//return null;

//抛异常

throw new Exception(“Jedis不能为空”);

}

}

/**

* 关闭Jedis对象

*/

public static void close(Jedis jedis) {

if(jedis != null){

jedis.close();

}

}

}



jedis.properties

maxTotal=10

maxWaitMillis=2000

host=127.0.0.1

port=6379

目前为止,我们用过的工具类很多了

04 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
<%@ page language=“java” import=“java.util.*” pageEncoding=“UTF-8”%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>

<html>

<head>

<title>My JSP ‘index.jsp’ starting page</title>

<meta http-equiv=“pragma” content=“no-cache”>

<meta http-equiv=“cache-control” content=“no-cache”>

<meta http-equiv=“expires” content=“0”>

<meta http-equiv=“keywords” content=“keyword1,keyword2,keyword3”>

<meta http-equiv=“description” content=“This is my page”>

<!– 引入JQJS文件 –>

<script type=“text/javascript” src=“js/jquery-1.11.3.min.js”></script>

</head>

<body>



<select id=“provinceID”>

<option>选择省份</option>

<%–当浏览器加载index.jsp页面时,动态加载省份–%>

</select>





<script type=“text/javascript”>

//当浏览器加载index.jsp页面时,动态加载省份

$(function(){

//发送AJAX请求

var url = “${pageContext.request.contextPath}/ProvinceServlet”;

var data = null;

var callback = function(backData){//[{“pid”:1,”pname”:”湖南”},{“pid”:2,”pname”:”广东”}]

//用JS语法来解析JSON对象

for(var i=0;i<backData.length;i++){

//获取每个JSON对象的pid

var pid = backData[i].pid;

//获取每个JSON对象的pname

var pname = backData[i].pname;

//创建option标签

var $option = $(“<option value='” + pid + “‘>” + pname + “</option>”);

//将option标签添加到select标签中

$(“#provinceID”).append( $option );

}//for-end

};

var type = “json”;

$.post(url,data,callback,type);

});

</script>



</body>

</html>
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package com.itheima.redis.web;



import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.itheima.redis.service.ProvinceService;

import com.itheima.redis.util.PrintUtil;



/**

* web层

*/

public class ProvinceServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

}

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

try {

request.setCharacterEncoding(“UTF-8”);

//创建业务层对象,并调用方法

ProvinceService service = new ProvinceService();

String provinceListJSON = service.findAllProvince();

//用IO形式将JSON字符串输出到客户端

PrintUtil.toClient(provinceListJSON,response);

} catch (Exception e) {

e.printStackTrace();

request.setAttribute(“MESSAGE”,“查询所有省份失败”);

request.getRequestDispatcher(“/WEB-INF/message.jsp”).forward(request,response);

}

}

}



package com.itheima.redis.service;



import java.util.List;

import redis.clients.jedis.Jedis;

import com.google.gson.Gson;

import com.itheima.redis.dao.ProvinceDao;

import com.itheima.redis.entity.Province;

import com.itheima.redis.util.JedisUtil;



/**

* service层

*/

public class ProvinceService {

private ProvinceDao dao = new ProvinceDao();

/**

* 查询所有省份

*/

public String findAllProvince() throws Exception{

//获取Jedis对象

Jedis jedis = JedisUtil.getJedis();

//根据key去Redis中找到对应value

String provinceListJSON = jedis.get(“PROVINCE_LIST_JSON”);

//如果key存在

if(provinceListJSON != null){

System.out.println(“去Redis中取”);

//关闭Jedis对象

JedisUtil.close(jedis);

//返回

return provinceListJSON;

//如果key不存在

}else{

System.out.println(“去MySQL中取”);

//调用持久层对象的方法

List<Province> provinceList = dao.findAllProvince();

//为了让以后,少查MySQL,我们将List集合转成JSON字符串

Gson gson = new Gson();

provinceListJSON = gson.toJson(provinceList);

//存入Redis中

jedis.set(“PROVINCE_LIST_JSON”,provinceListJSON);

//关闭Jedis对象

JedisUtil.close(jedis);

//返回

return provinceListJSON;

}

}

}



package com.itheima.redis.dao;



import java.sql.SQLException;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.itheima.redis.entity.Province;

import com.itheima.redis.util.JdbcUtil;



/**

* dao层

*/

public class ProvinceDao {

/**

* 查询所有的省份

*/

public List<Province> findAllProvince() throws SQLException{

//创建QueryRunner对象

QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());

//创建SQL语句

String sql = ” SELECT *” +

” FROM tab_province” +

” ORDER BY pid ASC”;

//创建数组

Object[] params = null;

//执行SQL语句

return runner.query(sql,new BeanListHandler<Province>(Province.class),params);

}

}



package com.itheima.redis.entity;



/**

* 省份

* 与

* tab_province表一一对应

*/

public class Province implements java.io.Serializable{

private int pid;//编号

private String pname;//名字

public Province(){}

public int getPid() {

return pid;

}

public void setPid(int pid) {

this.pid = pid;

}

public String getPname() {

return pname;

}

public void setPname(String pname) {

this.pname = pname;

}

}



package com.itheima.redis.util;



import com.mchange.v2.c3p0.ComboPooledDataSource;



/**

* Jdbc工具类

*/

public final class JdbcUtil {

private JdbcUtil(){}

/**

* 去src/c3p0–config.xml文件

*/

private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

/**

* 获取DataSource

*/

public static ComboPooledDataSource getDataSource() {

return dataSource;

}

}



package com.itheima.redis.util;



import java.util.ResourceBundle;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;



/**

* Jedis工具类

*/

public final class JedisUtil {

private static JedisPool pool;

private static String maxTotal;

private static String maxWaitMillis;

private static String host;

private static String port;

/**

* 读取src/jedis.properties属性文件中的内容

*/

static{

//ResourceBundle专用于去类路径下找*.properties文件,所以扩展名properties可以不写

//建议项目中的配置文件放在src目录下

ResourceBundle rb = ResourceBundle.getBundle(“jedis”);

//根据key找value

maxTotal = rb.getString(“maxTotal”);

maxWaitMillis = rb.getString(“maxWaitMillis”);

host = rb.getString(“host”);

port = rb.getString(“port”);

}

/**

* 创建连接池对象

*/

static{

JedisPoolConfig config = new JedisPoolConfig();

config.setMaxTotal(Integer.parseInt(maxTotal));

config.setMaxWaitMillis(Integer.parseInt(maxWaitMillis));

pool = new JedisPool(config,host,Integer.parseInt(port));

}

private JedisUtil(){

}

/**

* 获取Jedis对象

*/

public static Jedis getJedis() throws Exception{

//如果连接池非空

if(pool != null){

//从连接池中获取Jedis对象

return pool.getResource();

}else{

//return null;

//抛异常

throw new Exception(“Jedis不能为空”);

}

}

/**

* 关闭Jedis对象

*/

public static void close(Jedis jedis) {

if(jedis != null){

jedis.close();

}

}

}



package com.itheima.redis.util;



import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;



/**

* 向客户端输出内容

*/

public final class PrintUtil {

private PrintUtil(){}

public static void toClient(String content,HttpServletResponse response) throws Exception{

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter pw = response.getWriter();

pw.write(content);

pw.flush();

pw.close();

}

}