使用Java代码操作 Redis
一、在pom.xml里添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
二、测试是否成功连接Redis
Jedis jedis = new Jedis("192.168.80.132",6379);
jedis.auth("123456");
System.out.println(jedis.ping());
这就表示连接成功了
三、操作数据
操作字符串:
/**
* string
*/
jedis.set("name","zs");
jedis.set("age","23");
System.out.println(jedis.get("name"));
操作哈希
/**
* hash
*/
jedis.hset("use1","uname","ls");
jedis.hset("use1","pwd","123456");
jedis.hset("use1","set","nan");
System.out.println(jedis.hget("use1", "uname"));
Map<String, String> use1 = jedis.hgetAll("use1");
for (Map.Entry<String, String> entry : use1.entrySet()) {
System.out.println("key:" + entry.getKey() + ",value" + entry.getValue());
}
操作list
jedis.lpush("hobby","a","b","c","d","e");
System.out.println(jedis.lpop("hobby"));
System.out.println(jedis.lpop("hobby"));
System.out.println(jedis.rpop("hobby"));
查询中使用redis的逻辑图解:
redis在增删改中的使用的图解:
bookservlet.jsp:
package com.zking.redis;
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 Lebron
* @site
* @company
* @create 2019-10-13 下午 11:15
*/
@WebServlet("/zhou")
public class bookservlet 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.80.132",6379);
jedis.auth("123456");
String booklist = jedis.get("booklist");
if(booklist==null || "".equals(booklist)){
//模拟实际项目开发需求,在项目中运用redis
//查询数据库
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("/index.jsp").forward(req,resp);
}
}
}
index.jsp
<html>
<body>
<h2>Hello World!</h2>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019-10-13
Time: 下午 11:30
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>
${mag}:${booklist}
</body>
</html>