1. Java访问redis
1 添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2Java连接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命令
java操作Redis赋值取值案例
package com.qukang;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import java.util.Map;
/**
* @author 屈康
* @site www.qk.com
* @company 不讲理公司
* @create 2019-10-13 11:43
*
* 讲解java代码操作redis
* String
* hash
* list
*/
public class Dome1 {
public static void main(String[] args) {
Jedis jedis=new Jedis("192.168.195.128",6379);
jedis.auth("123456");
System.out.println(jedis.ping());
/*
string
*/
jedis.set("name","zs");
// jedis.set("age","22");
// System.out.println(jedis.get("name"));
/*
hash
*/
// jedis.hset("user1","uname","ls");
// jedis.hset("user1","pwd","123456");
// jedis.hset("user1","set","nv");
// System.out.println(jedis.hget("user1", "uname"));
// 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"));
// System.out.println(jedis.rpop("hobby"));
}
}
通过查询体现Redis在项目中的使用
package com.qukang;
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 屈康
* @site www.qk.com
* @company 不讲理公司
* @create 2019-10-13 12:03
*
* redis在项目中使用
* 查询
* 增删改
*/
@WebServlet("/list")
public class Servlet 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 jedis=new Jedis("192.168.195.128",6379);
jedis.auth("123456");
String bookList=jedis.get("bookList");
if(null==bookList || "".equals(bookList)){
// 查询数据库
String mysqlData="data";
// 讲mysqlData转成json数组串
jedis.set("bookList",mysqlData);
bookList=jedis.get("bookList");
req.setAttribute("mag","走了数据库数据");
req.setAttribute("booklist",bookList);
req.getRequestDispatcher("/booklist.jsp").forward(req,resp);
// 转成对象
// 转发页面
}else{
req.setAttribute("mag","直接从redis里面拿了数据");
req.setAttribute("booklist",bookList);
req.getRequestDispatcher("/booklist.jsp").forward(req,resp);
}
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${mag}:${booklist}
</body>
</html>
第一次访问从数据库里拿值
第二次访问从Redis缓存里拿值
2.项目实战
添加依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qukang</groupId>
<artifactId>Redis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Redis Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<servlet.version>4.0.0</servlet.version>
<mysql.version>5.1.44</mysql.version>
<jstl.version>1.2</jstl.version>
<standard.version>1.1.2</standard.version>
<tomcat-jsp.version>8.0.47</tomcat-jsp.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat-jsp.version}</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
<build>
<finalName>Redis</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
BookAction.java
package com.qukang.web;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.qukang.dao.BookDao;
import com.qukang.entity.Book;
import com.qukang.framework.ActionSupport;
import com.qukang.framework.ModelDrivern;
import redis.clients.jedis.Jedis;
public class BookAction extends ActionSupport implements ModelDrivern<Book>{
private Book book = new Book();
private BookDao bookDao = new BookDao();
/**
* 分页查询
* @param req
* @param resp
* @return
*/
public String list(HttpServletRequest req,HttpServletResponse resp) {
try {
List<Book> list = this.bookDao.list(book, null);
Jedis jedis=new Jedis("192.168.195.128",6379);
jedis.auth("123456");
String booklist = jedis.get("booklist");
if(booklist==null || "".equals(booklist)){
System.out.println("先从mysql数据库拿");
String mysqldata= JSON.toJSONString(list);
jedis.set("booklist",mysqldata);
booklist = jedis.get("booklist");
req.setAttribute("bookList",list);
}else{
System.out.println("直接从redis拿");
req.setAttribute("bookList", JSON.parse(booklist));
/*jedis.del("booklist");
System.out.println("查询方法更新缓存");*/
}
} catch (InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
/**
* 跳转到增加或者修改页面
* @param req
* @param resp
* @return
*/
public String preSave(HttpServletRequest req,HttpServletResponse resp) {
// bid的类型是int类型,而int类型的默认值是0,如果jsp未传递bid的参数值,那么bid=0
if(book.getBid() == 0) {
System.out.println("增加逻辑.....");
}else {
// 修改数据回显逻辑
try {
// 查单个
Book b = this.bookDao.list(book, null).get(0);
req.setAttribute("book", b);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
// 新增页面与修改页面是同一个jsp
return "edit";
}
/**
* 新增
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
int code= this.bookDao.add(book);
if(code>0){
// 更新缓存
Jedis jedis=new Jedis("192.168.195.128",6379);
jedis.auth("123456");
jedis.del("booklist");
System.out.println("增加方法已执行");
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 新增完了后需要刷新页面
return "toList";
}
/**
* 修改
* @param req
* @param resp
* @return
*/
public String edit(HttpServletRequest req,HttpServletResponse resp) {
try {
int code= this.bookDao.edit(book);
if(code>0){
Jedis jedis=new Jedis("192.168.195.128",6379);
jedis.auth("123456");
jedis.del("booklist");
System.out.println("修改方法已执行");
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 修改完了后需要刷新页面
return "toList";
}
/**
* 删除
* @param req
* @param resp
* @return
*/
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
int code= this.bookDao.del(book);
if(code>0){
Jedis jedis=new Jedis("192.168.195.128",6379);
jedis.auth("123456");
jedis.del("booklist");
System.out.println("删除方法已执行");
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel() {
return book;
}
}
bookList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="/leiyuanlin" prefix="z" %>
<!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>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
<br>
<form action="${pageContext.request.contextPath}/book.action?methodName=list"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
<input type="hidden" name="rows" value="15">
</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>
<%--<z:page pageBean="${pageBean }"></z:page>--%>
</body>
</html>
从数据库拿
从Redis中拿
操作进程