文章目录
1、 Java访问redis
1.1、添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
如图1
1.2、Java连接redis
Jedis jedis = new Jedis(ip, port);
jedis.auth("123456");//权限认证
jedis.ping();
jedis.select(0);//切换数据库
1.3、Java操作redis
string(字符串)
hash(哈希)
list(列表)
set(集合)
zset(sorted set:有序集合)
zadd/zrevrange
注1:不需要记得API的方法,只需要查redis命令
代码演示:
package com.qwf;
import redis.clients.jedis.Jedis;
import java.lang.reflect.Field;
/**
* @author qwf
* @site www.qwf.com
* @company
* @create 2019-11-13 11:03
*/
public class Demo1 {
public static void main(String[] args) {
Jedis jedis = new Jedis("122.51.214.193",6379);
jedis.auth("123123");
// 校验redis服务正常,然后通过jedis连接服务正常
// System.out.println(jedis.ping());
// 操作string
// jedis.set("sname","zsf");
// System.out.println(jedis.get("sname"));
// 操作hash
// 所有的值都在user中
// 1.存值
User user = new User("ww","人妖","changsha","360231...");
for (Field field : user.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
System.out.println(field.getName() + ":" + field.get(user).toString());
jedis.hset("user1",field.getName(),field.get(user).toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
// 2.取值
// 2.1 单个
// System.out.println(jedis.hget("user1","usex"));
// 2.2 多个
// Map<String, String> user1 = jedis.hgetAll("user1");
// for (Map.Entry<String, String> entry : user1.entrySet()) {
// System.out.println(entry.getKey() + " : " + entry.getValue());
// }
// 操作list
// jedis.lpush("hobby","a","b","c","d","e","f","g");
// System.out.println(jedis.lpop("hobby"));
// System.out.println(jedis.rpop("hobby"));
}
}
set(集合)
hash(哈希)
1.存值
2.取值
2.1 单个
2.2 多个
list(列表)
1.第一次
2.第二次
2、mvc的那个工程的首页改成读取redis数据
web.xml文件
初次使用idea建立web项目时,你可能会遇到不能使用el表达式
解决方法一:(推荐)
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
解决方法二:
<%@ page isELIgnored="false"%>
2.1、首页第一次是读取数据库,后面读取缓存(在没有增删改的情况)
package com.qwf;
import redis.clients.jedis.Jedis;
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 qwf
* @site www.qwf.com
* @company xxx公司
* @create 2019-11-13 19:33
*/
@WebServlet("/list")
public class BookListServlet 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 {
// 先从redis里面去书籍的前十条数据
Jedis jedis = new Jedis("122.51.214.193",6379);
jedis.auth("123123");
// 字符串bookList存放的是,json数据字符串 List<Book> -->json
// 如果需要通过json数组传做jsp页面展示的话,需要将json数据字符串--->List<Book> jackSon
String bookList = jedis.get("bookList");
if (null == bookList || "".equals(bookList)){
// 此时意味着是第一次查询,那么需要走数据库MySQL
System.out.println("先走数据库做书籍列表的查询...");
String list = "从MySQL数据库中查询出十条数据,再转成json串...";
jedis.set("bookList",list);
req.setAttribute("jspList","数据来源于MySQL:" + jedis.get("bookList"));
}else {
// 意味着不是第一次查询,那么就可以将数据返回了
req.setAttribute("jspList","数据来源于redis:" + bookList);
}
req.getRequestDispatcher("bookList.jsp").forward(req,resp);
}
}
2.2、项目实例
BookAction.java
package com.qwf.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.qwf.dao.BookDao;
import com.qwf.entity.Book;
import com.qwf.framework.ActionSupport;
import com.qwf.framework.ModelDriver;
import com.qwf.util.PageBean;
import com.qwf.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 获取数据到页面所需的时间