Java访问redis
1 .添加pom依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2 .Java连接redis
Jedis jedis = new Jedis(ip, port);
jedis.auth("123456");//权限认证
jedis.ping();
jedis.select(0);//切换数据库
3. Java操作redis
string(字符串)
hash(哈希)
list(列表)
set(集合)
zset(sorted set:有序集合)
zadd/zrevrange
注1:不需要记得API的方法,只需要查redis命令
Demo1
package com.cjq.redis;
import redis.clients.jedis.Jedis;
import java.util.Map;
/**
* @author cjq
* @create 2019-11-14 18:23
*
* 讲解java代码操作redis
* String Hash List
*
* mysql连接数据库方式
* 1.加载驱动
* 2.建立连接(url/uname/pwd)
* 3.preparestatement(预定义对象)
* 4.执行sql
* 5.处理结果
* 6.关闭资源
*
* redis连接步骤
* 1.建立连接,连接后授权
* 2.使用redis
*/
public class Demo1 {
public static void main(String[] args) {
//建立连接 使用jedis 输入ip和端口号
Jedis jedis=new Jedis("192.168.163.196",6379);
//授权
jedis.auth("123456");
//使用
//检测是否可以使用
System.out.println(jedis.ping());//PONG代表成功
/**
* String
*/
//设置值,既加入,再次加入同一个键的不同值时不会加入,会修改原来的值
// jedis.set("name","zs");
// jedis.set("age","22");
//获取值
// System.out.println( jedis.get("name"));
/**
* Hash 对象
*/
//设置值
// jedis.hset("user1","uname","wanwu");
// jedis.hset("user1","pwd","123456");
// jedis.hset("user1","sex","nan");
// //取值
// System.out.println(jedis.hget("user1","uname"));//获取user1中的uname的值
// System.out.println(jedis.hgetAll("user1"));//获取user1中的全部值
// Map<String, String> user1 =jedis.hgetAll("user1");
// for (Map.Entry<String, String> entry : user1.entrySet()) {
// System.out.println("key:"+entry.getKey()+" !! "+"value:"+entry.getValue());
// }
/*
* List
* */
jedis.lpush("hobby","a","b","c","d","e","f","g");
System.out.println(jedis.lpop("hobby"));
}
}
DemoServlet
package com.onlyK.redis;
import redis.clients.jedis.Jedis;
import javax.print.DocPrintJob;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author cjq
* @create 2019-11-14 18:51
*
* 讲解reids在项目中的使用
* 查询
*
*/
@WebServlet("/list")
public class DemoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//建立连接 使用jedis 输入ip和端口号
Jedis jedis=new Jedis("192.168.163.196",6379);
//授权
jedis.auth("123456");
String bookList = jedis.get("bookList");
if(null == bookList || "".equals(bookList)){//如果没有
//查询数据库
String mysqlData="数据查询出来了";
//给到redis
jedis.set("bookList",mysqlData);
bookList=jedis.get("bookList");
req.setAttribute("msg","走数据库");
req.setAttribute("bookList",bookList);
//跳页面展示
req.getRequestDispatcher("/bookList.jsp").forward(req,resp);
}else{//如果有 走redis
req.setAttribute("msg","走redis");
req.setAttribute("bookList",bookList);
//跳页面展示
req.getRequestDispatcher("/bookList.jsp").forward(req,resp);
}
}
}
jsp页面
<%--
Created by IntelliJ IDEA.
User: 123456
Date: 2019/11/14
Time: 18:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>数据列表</title>
</head>
<body>
拿取数据的方式:${msg}<br>
拿取到的数据:${currentUser}
</body>
</html>
项目操作
1.查询中使用Redis的逻辑
2.Redis在增删改查的使用
BookAction.java
package com.cjq.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cjq.dao.BookDao;
import com.cjq.entity.Book;
import com.cjq.framework.ActionSupport;
import com.cjq.framework.ModelDriver;
import com.cjq.util.PageBean;
import com.cjq.util.StringUtils;
import redis.clients.jedis.Jedis;
public class BookAction extends ActionSupport implements ModelDriver<Book> {
private Book book = new Book();
private BookDao bookDao = new BookDao();
private static final String HOST = "192.168.163.196";
private static final int PORT = 6379;
private static Jedis jedis;
static {
jedis = new Jedis(HOST, PORT);
jedis.auth("cjq@1123");
}
public String list(HttpServletRequest req, HttpServletResponse resp) {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
try {
// 获取redis中 key :bookList 对应的value值
String bookList = jedis.get("bookList");
// 第一次查询走数据库
if(StringUtils.isBlank(bookList)) {
List<Book> list = this.bookDao.list(book, pageBean);
System.out.println("-----第一次查询走的数据库-------");
// 把从数据库查询的数据转换成josn格式存入 redis String zhong
String bookJosn = JSON.toJSONString(list);
jedis.set("bookList",bookJosn);
req.setAttribute("bookList", list);
}else {
// 第二次查询走redis
System.out.println("-----第二次查询走redis-------");
req.setAttribute("bookList",JSON.parse(bookList));
}
req.setAttribute("pagebean", pageBean);
} catch (Exception e) {
e.printStackTrace();
}finally {
jedis.close();
}
return "list";
}
/**
* 跳转新增修改页面(新增修改是同一个)
*
* @param req
* @param resp
* @return
* @throws Exception
*/
public String preSave(HttpServletRequest req, HttpServletResponse resp) {
if (book.getBid() != 0) {
try {
Book b = this.bookDao.list(book, null).get(0);
req.setAttribute("book", b);
} catch (Exception e) {
e.printStackTrace();
}
}
return "edit";
}
/**
* 新增
*
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
System.out.println("增加一条书籍记录,清空了redis 的缓存");
this.bookDao.add(book);
jedis.del("bookList");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
jedis.close();
}
return "toList";
}
public String edit(HttpServletRequest req, HttpServletResponse resp) {
try {
this.bookDao.edit(book);
jedis.del("bookList");
System.out.println("修改一条书籍记录,清空了redis 的缓存");
} catch (Exception e) {
e.printStackTrace();
}finally {
jedis.close();
}
return "toList";
}
public String del(HttpServletRequest req, HttpServletResponse resp) {
try {
this.bookDao.del(book);
jedis.del("bookList");
System.out.println("删除一条书籍记录,清空了redis 的缓存");
} catch (Exception e) {
e.printStackTrace();
}finally {
jedis.close();
}
return "toList";
}
public Book getModel() {
return book;
}
// 测试连接是否成功
public static void main(String[] args) {
// System.out.println(jedis.ping());
// jedis.close();
// String userString = "{\"name\":\"ZhangSan\",\"sex\":\"ZhangSan\"}";
// JSONObject userJson = JSONObject.parseObject(userString);
// System.out.println(userJson);
}
}
bookList.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/cbw" prefix="b"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>读取redis数据</title>
</head>
<body>
<h2>小说目录</h2>
<br>
<form action="${pageContext.request.contextPath}/book.action?methodName=list" method="post">
<!--用户设置查询 一页20条记录 -->
<!-- <input type="hidden" name="rows" value="20"/> -->
<!--用户设置不分页 -->
<!-- <input type="hidden" name="pagination" value="false"/> -->
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<a href="${pageContext.request.contextPath}/book.action?methodName=preSave">增加</a>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>操作</td>
</tr>
<c:forEach items="${bookList}" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<a href="${pageContext.request.contextPath}/book.action?methodName=preSave&&bid=${b.bid }">修改</a>
<a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<b:page pageBean="${pagebean}"></b:page>
</body>
</html>
bookEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>编辑页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book.action?methodName=${book.bname == null ?'add' : 'edit'}" method="post">
bid: <input type="text" value="${book.bid}" name="bid"/><br>
bname:<input type="text" value="${book.bname}" name="bname"/><br>
price:<input type="text" value="${book.price}" name="price"/><br>
<button type="submit">确认</button>
</form>
</body>
</html>
结果如下:
从数据库获取数据到页面所需的时间
从redis 获取数据到页面所需的时间