使用java代码操作Redis
1导入pom.xml依赖
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2,Java代码操作一下存值取值
public class demo1 { public static void main(String[] args) { Jedis Jedis = new Jedis("192.168.171.129", 6379); Jedis.auth("123456"); // System.out.println(Jedis.ping()); //选择数据库 String select = Jedis.select(0); //Strng 字符串 //set // Jedis.set("name","张三"); //get获取 //System.out.println(Jedis.get("name")); //type获取类型 //System.out.println(Jedis.type("name")); //del删除 //Jedis.del("name"); //expire设置超时时间 //Jedis.expire("name",10); //hash(哈希) // Jedis.hset("student","name","李四"); // Jedis.hset("student","age","13"); // Jedis.hset("student","addres","长沙"); // System.out.println(Jedis.hget("student", "name")); //list列表 // Jedis.lpush("names","张三","李四","王五"); // Long names = Jedis.llen("names"); // for (int i=0;i<names;i++){ //// 从左到右 // System.out.println(Jedis.lpop("names")); //// 从左到右 // System.out.println(Jedis.rpop("names")); // } //set集合 // Jedis.sadd("username","admin","zs","ls"); // ScanResult<String> username = Jedis.sscan("username", 0); // List<String> result = username.getResult(); // for (String s : result) { // System.out.println(s); // } //zset有序集合 // Jedis.zadd("sex",70,"男"); // Jedis.zadd("sex",80,"女"); // Jedis.zadd("sex",90,"不男不女"); // ScanResult<Tuple> zscan = Jedis.zscan("sex", 0); // List<Tuple> result = zscan.getResult(); // for (Tuple tuple : result) { // System.out.println("sex="+tuple.getElement()+",score="+tuple.getScore()); // // } } }
DemoServerlet.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; @WebServlet("/list") public class DemoServerlet 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.171.129", 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("/bookList.jsp").forward(req,resp); } } }
bookList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> ${mag}:${booklist} </body> </html>
今天就到这里了谢谢大家!