使用redis ,要在pom.xml里添加依赖包:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
操作
Demo
import redis.clients.jedis.Jedis;
/**
* @author XZY
* @site www.Xzy.com
* @company
* @create 2019-09-18 16:51
*
* 连接redis
* 操作字符串
* 操作哈希
* 操作list
*
*/
public class Demo1 {
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.200.128",6379);
jedis.auth("123456");
// System.out.println(jedis.ping());
//操作字符串
// jedis.set("name","dog");//存
// System.out.println(jedis.get("name"));//取
//操作哈希
// jedis.hset("user1","dname","cat");
// jedis.hset("user1","sex","男");
// System.out.println(jedis.hgetAll("user1"));//取整个对象
// System.out.println(jedis.hget("user1", "dname"));//去对象的一个属性
//操作列表
jedis.lpush("hobby","SING","DANCE","RAP","BALL");
// System.out.println(jedis.lpop("hobby"));//取最上面的
// System.out.println(jedis.lpop("hobby"));//若重复使用,则取下一个
// System.out.println(jedis.rpop("hobby"));//取最下面的
}
}
案例
home.jsp
<%--
Created by IntelliJ IDEA.
User: lenovo
Date: 2019/9/19
Time: 14:43
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</title>
</head>
<body>
博客首页
拿取数据的方式:${msg}<br>
去到的数据:${currentUser}
</body>
</html>
DemoServlet.java
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;
import java.util.Map;
/**
* @author XZY
* @site www.Xzy.com
* @company
* @create 2019-09-19 14:44
*/
@WebServlet("/get")
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 jedis = new Jedis("192.168.200.128",6379);
jedis.auth("123456");
//从缓存获取当前登录的用户信息
Map<String,String> currentUser = jedis.hgetAll("currentUser");
if(currentUser != null && currentUser.size()>0){
req.setAttribute("msg","从缓存获取数据");
req.setAttribute("currentUser",currentUser);
}else{
//第一次登录,访问数据库
req.setAttribute("msg","从数据库获取数据");
String uname = "dog";
String upwd = "123456";
//把数据库中对应的对象存到缓存中
jedis.hset("currentUser","uname",uname);
jedis.hset("currentUser","upwd",upwd);
//此时能获取到值的原因是已经将数据储存到缓存中
currentUser = jedis.hgetAll("currentUser");
req.setAttribute("currentUser",currentUser);
}
req.getRequestDispatcher("home.jsp").forward(req,resp);
}
}
无增删改,然后再次进入的时候,读取缓存的数据