redis实例

启动连接redis

在这里插入图片描述
通过此命令启动redis服务直到出现pong

./src/redis-server redis.conf
./src/redis-cli
./src/redis-cli -h 127.0.0.1 -p 6379 -a 123456

在这里插入图片描述

导入依赖

     <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
      </dependency>

java连接redis

 public static void main(String[] args) {
        // 创建连接
        Jedis jedis = new Jedis("140.143.xxx.xxx",6379);
        // 设置密码
        jedis.auth("xxxxxxx");
        // 调用 ping 方法 校验redis 服务正常和连接redis 连接服务正常
        System.out.println(jedis.ping());
        // 关闭
        jedis.close(); 
    }

控制台输出了 PONG 代表成功

java 操作 redis

package com.wxm;

/**
 * @author wxm
 * @site www.wxm.com
 * @company xxx公司
 * @create 2019-11-16 17:07
 */
public class aaa {
    public static void main(String[] args) {
//        创建连接
        Jedis jedis = new Jedis("192.168.192.130", 6379);
//         设置密码
        jedis.auth("123456");
//       调用 ping 方法 ,校验redis 服务正常和连接redis 连接服务正常
//       /System.out.println(jedis.ping());

//     操作String
//       设置值
        jedis.set("sname", "zs");
//       获取值
        System.out.println(jedis.get("sname"));

//     操作 hash
//         所有的值在user中
//         User user = new User("ls","男","18","4306242");
//
//        for (Field field : user.getClass().getDeclaredFields()) {
//            field.setAccessible(true);
//            try {
//                System.out.println(field.getName()+" : "+field.get(user).toString());
//                jedis.hset("user1",field.getName(),field.get(user).toString());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//      取值
        // 取单个值
//         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(entry.getKey() + " : " + entry.getValue());
//        }

//     操作 list
        // left 左边 reght 右边
        jedis.lpush("bobby","a","b","c","d","e","f","g");

        System.out.println(jedis.lpop("bobby"));
        System.out.println(jedis.rpop("bobby"));

        // 关闭
        jedis.close();
    }



}

使用redis优化简答的mvc项目

在这里插入图片描述
bookList.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/wxm"  prefix="h"%>
<!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>书籍主页</title>
</head>
<body>
<h2>小说目录</h2>
	<br>
	<form action="${pageContext.request.contextPath}/book.action?methodName=list" method="post">
		<!--用户设置查询 一页20条记录  -->
	 <!-- 	<input type="hidden" name="rows" value="20"/> -->
		<!--用户设置不分页  -->
	 	<!-- <input type="hidden" name="pagination" value="false"/> -->
		书名:<input type="text" name="bname"> <input type="submit"
			value="确定">
	</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>
<%-- <h:page pageBean="${pagebean}"></h:page> --%>
</body>
</html>

BookAction

package com.wxm.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wxm.dao.BookDao;
import com.wxm.entity.Book;
import com.wxm.framework.ActionSupport;
import com.wxm.framework.ModelDriver;
import com.wxm.util.PageBean;
import com.wxm.util.StringUtils;

import redis.clients.jedis.Jedis;

public class BookAction extends ActionSupport implements ModelDriver<Book> {
	private Book book = new Book();
	private BookDao bookDao = new BookDao();

	private static final String HOST = "192.168.192.130";
	private static final int PORT = 6379;

	private static Jedis jedis;
	static {
		jedis = new Jedis(HOST, PORT);
		jedis.auth("123456");
	}

	public String list(HttpServletRequest req, HttpServletResponse resp) {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		try {
			// 获取redis中的key:bookList对应的value值
			String bookList = jedis.get("bookList");

			// 第一次查询走数据库
			if (StringUtils.isBlank(bookList)) {
				List<Book> list = this.bookDao.list(book, pageBean);
				System.out.println("-----第一次走数据库---------");
				// 把从数据库查询的数据转换成json格式存入redis 
				String bookJson = JSON.toJSONString(list);
				jedis.set("bookList", bookJson);
				req.setAttribute("bookList", list);
			} else {
				// 第二次查询走redis
				System.out.println("-----第二次查询走redis---------");
				req.setAttribute("bookList", JSON.parse(bookList));
			}
			req.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jedis.close();
		}
		return "list";
	}

	/**
	 * 跳转新增修改页面(新增修改是同一个)
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	public String preSave(HttpServletRequest req, HttpServletResponse resp) {
		if (book.getBid() != 0) {
			try {
				Book b = this.bookDao.list(book, null).get(0);
				req.setAttribute("book", b);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "edit";
	}

	/**
	 * 新增
	 * 
	 * @param req
	 * @param resp
	 * @return
	 */
	public String add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			System.out.println("增加一条书籍记录,清空了redis 的缓存");
			this.bookDao.add(book);
			jedis.del("bookList");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}

	public String edit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.bookDao.edit(book);
			jedis.del("bookList");
			System.out.println("修改一条书籍记录,清空了redis 的缓存");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}

	public String del(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.bookDao.del(book);
			jedis.del("bookList");
			System.out.println("删除一条书籍记录,清空了redis 的缓存");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}

	public Book getModel() {
		return book;
	}

	// 测试连接是否成功
	public static void main(String[] args) {
		System.out.println(jedis.ping());
		jedis.close();
		String userString = "{\"name\":\"ZhangSan\",\"sex\":\"ZhangSan\"}";
		JSONObject userJson = JSONObject.parseObject(userString);
		System.out.println(userJson);
	}
}

1.需要导入夹包(jedis 和 fastjosn)

在这里插入图片描述

2.查询和修改思路图解

在这里插入图片描述
在这个案例上做reids缓存的优化,只需要改部分代码自定义MVC(增删改查

1.eclipse连接redis成功
在这里插入图片描述
查看是否走了redis在这里插入图片描述
第一次访问数据库,未使用redis
在这里插入图片描述
第二次查询,使用redis后在这里插入图片描述

结论:大大提高了查询的速度与性能

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值