java操作redis

Redis-安装和命令操作

(https://blog.csdn.net/qq_45174759/article/details/102525843)上,演示Redis使用Java代码操作,以及在项目中的实际应用。

使用Java代码操作Redis
Demo1.java
代码如下:

package com.chenkang;

import redis.clients.jedis.Jedis;

/**
 * @author陈康
 * @site www.chenkang.com
 * @company xxx公司
 * @create  2019-10-13 10:29
 */
public class Demo1 {
    public static void main(String[] args) {
        Jedis jedis=new Jedis("192.168.149.129",6379);
        jedis.auth("123456");

        System.out.println(jedis.ping());

        /*
        String(字符串)
         */
        //存值
//        jedis.set("name","hc");
//        jedis.set("sex","男");
        //取值
//        System.out.println(jedis.get("name"));


        /*
        哈希(Hash)
         */
//        jedis.hset("user","name","hc");
//        jedis.hset("user","sex","男");
//        jedis.hset("user","age","20");
//        jedis.hset("user","pwd","375199");
//        System.out.println(jedis.hget("user","naem"));
//        Map<String, String> user = jedis.hgetAll("user");
//        for (Map.Entry<String, String> e : user.entrySet()) {
//            System.out.println("key:"+e.getKey()+",value:"+e.getValue());
//        }
        /*
        列表(List)
         */
        jedis.lpush("hobby","a","b","c","d");
        System.out.println(jedis.lpop("hobby"));
        System.out.println(jedis.rpop("hobby"));


    }
}


项目中的应用演示例子
查询中使用redis的逻辑
如图所示:
在这里插入图片描述
redis在增删改中的使用
如图所示:
在这里插入图片描述
Demoservlet.java
代码如下:

package com.chenkang;

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.hc.com
 * @company xxx公司
 * @create  2019-10-14 01:13
 */
@WebServlet("/demo1")
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.149.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

<%--
  Created by IntelliJ IDEA.
  User: machenike
  Date: 2019/10/13
  Time: 11:53
  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>


效果如图所示:
第一次访问
在这里插入图片描述
第二次访问
在这里插入图片描述

项目实战演示(利用的是原生mvc框架演示)

BookAction.java
代码如下:

package com.chenkang.web;

import com.alibaba.fastjson.JSON;
import com.hc.dao.BookDao;
import com..entity.Book;
import com.hc.framework.ActionSupport;
import com.hc.framework.ModelDrivern;
import com.hc.util.PageBean;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.List;

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) {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		try {
			List<Book> list = this.bookDao.list(book, pageBean);
			Jedis jedis=new Jedis("192.168.149.129",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);
				req.setAttribute("pageBean", pageBean);
			}else{
				System.out.println("直接从redis拿数据,很快");
				req.setAttribute("bookList", JSON.parse(booklist));
				req.setAttribute("pageBean", pageBean);
                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 add = this.bookDao.add(book);
            if(add>0){
                //			更新缓存
                Jedis jedis=new Jedis("192.168.149.129",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 edit = this.bookDao.edit(book);
            if(edit>0){
                //			更新缓存
                Jedis jedis=new Jedis("192.168.149.129",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 del = this.bookDao.del(book);
            if(del>0){
                //			更新缓存
                Jedis jedis=new Jedis("192.168.149.129",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;
	}
}


在这里插入图片描述
时间对比图。如图所示:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值