day11-【Redis】综合案例分析
(1)查询所有分类
》》1:请求Servlet
》》2:查询Redis
如果有数据直接返回
如果没有数据,调Service,调Dao,将返回的集合转成Json
再使用Redis保存
Redis适合用来保存经常被访问但是很少被修改的数据。
思路分析:
1:查询redis,没有json数据,就调用CategoryDao,去获取集合List
先返回给CategorySrvice,再转成json存进redis
2:第二次起,直接获取redis中的json,将json转成List
实现:
先test
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rh.Service.CategoryService;
import com.rh.bean.Category;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
//第一步:测试开发CategoryService
public class TestCategoryService {
@Test
public void test01() throws Exception {
//0: 创建业务类对象
CategoryService categoryService = new CategoryService();
//1: 查询分类集合
List<Category> list = categoryService.queryAll();
for(Category category:list){
System.out.println(category);
}
}
}
bean
package com.rh.bean;
//第二步骤 :
public class Category {
private int cid;
private String cname;
public Category(int cid, String cname) {
this.cid = cid;
this.cname = cname;
}
public Category() {
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@Override
public String toString() {
return "Category{" +
"cid=" + cid +
", cname='" + cname + '\'' +
'}';
}
}
CategoryService`
package com.rh.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rh.Dao.CategoryDao;
import com.rh.bean.Category;
import comm.rh.pack01.JedisUtils;
import redis.clients.jedis.Jedis;
import java.io.IOException;
import java.util.List;
//第三步骤:实现queryAll方法
//3.1 复制jedis jar过来
//3.2 绑定
//3.3 复制properties文件,与工具类
public class CategoryService {
CategoryDao dao = new CategoryDao();
ObjectMapper objectMapper = new ObjectMapper();
public List<Category> queryAll() throws IOException {
//queryAll的逻辑
//1:先访问redis,有数据就返回 JedisUtils Map<Srting,String>
//3.4获取连接
Jedis redis = JedisUtils.getRedis();
//缓存
String json = redis.get("list");
if(json == null){
System.out.println("第一次查询 redis没有数据,查的数据库的数据,慢");
//2: 没有数据就查询数据,进行缓存,方便下次使用 Cat egoryDao
List<Category> list = dao.findAll();
//缓存 将集合转换成json,缓存到redis
//3.5 添加json jar到lib目录并且绑定
//3.6 创建ObjectMapper对象,转list成json
String jsonValue = objectMapper.writeValueAsString(list);
System.out.println(jsonValue);
redis.set("list",jsonValue);
return list;
}else{//json ! =null
System.out.println("第二次 redis有数据,直接返回,快");
List<Category> list = objectMapper.readValue(json,new TypeReference<List<Category>>(){});//将json转成对象 参1 json数据 参2
return list;
}
}
}
CategoryDao
package com.rh.Dao;
import com.rh.bean.Category;
import java.util.ArrayList;
import java.util.List;
//第四步骤
public class CategoryDao {
public List<Category> findAll() {
//1:创建集合
List<Category> list = new ArrayList<>();
//使用循环模拟数据,以后使用mybatis来查数据
for (int i = 0; i < 10; i++) {
list.add(new Category(i,"分类名"+i));
}
return list;
}
}
将json数据转成对象
@Test
public void test02() throws IOException {
String json="[{\"cid\":0,\"cname\":\"分类名0\"},{\"cid\":1,\"cname\":\"分类名1\"},{\"cid\":2,\"cname\":\"分类名2\"},{\"cid\":3,\"cname\":\"分类名3\"},{\"cid\":4,\"cname\":\"分类名4\"},{\"cid\":5,\"cname\":\"分类名5\"},{\"cid\":6,\"cname\":\"分类名6\"},{\"cid\":7,\"cname\":\"分类名7\"},{\"cid\":8,\"cname\":\"分类名8\"},{\"cid\":9,\"cname\":\"分类名9\"}]";
//
ObjectMapper objectMapper = new ObjectMapper();
List<Category> list = objectMapper.readValue(json,new TypeReference<List<Category>>(){});//将json转成对象 参1 json数据 参2 new TypeReference<返回值类型>(){}
System.out.println(list);
}
参2 new TypeReference<返回值类型>()
过滤器解决全站中文编码乱码
package com.rh.Filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter( "/*")
public class ChsrSetFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
servlet
package com.rh.Servlet;
import com.rh.Service.CategoryService;
import com.rh.bean.Category;
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.List;
// /*表示拦截所有请求
@WebServlet("/*")
public class CategoryListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//0: 创建业务类对象
CategoryService categoryService = new CategoryService();
//1: 查询分类集合
List<Category> list = categoryService.queryAll();
//2: 请求转发
request.setAttribute("list",list);
request.getRequestDispatcher("list.jsp").forward(request,response);
}
}
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:forEach items="${list}" var="item">
<div > ${item.cname} </div>
</c:forEach>
</body>
</html>
工具类
package com.rh.Util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class JedisUtils {
private static JedisPool pool;
static {//静态代码在项目中,如果被使用只会加载一次
InputStream inputStream= JedisUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
Properties properties = new Properties();
try {
properties.load(inputStream);//将流中的数据读成map
} catch (IOException e) {
e.printStackTrace();
}
// 1:创建连接池的配置对象
JedisPoolConfig config = new JedisPoolConfig();
//设置最大链接数
config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
//设置空闲连接数 "3"
config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));
//2:创建连接池
pool = new JedisPool(config, properties.getProperty("url"), Integer.parseInt(properties.getProperty("port")));
}
public static Jedis getRedis() {
// 3:从连接池中获取一个连接
Jedis jedis = pool.getResource();//获取一个连接
return jedis;
}
public static void close(Jedis jedis) {
if(jedis!=null){
jedis.close();
}
}
}
jedis.properties文件
maxTotal=30
maxIdle=10
url=localhost
port=6379
``
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200921221750459.png#pic_center)
`jar包
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200921221824567.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JlblZpY3Rvcnk=,size_16,color_FFFFFF,t_70#pic_center)
js
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200921221834855.png#pic_center)