Redis Comprehensive Case-Use redis to realize the classification of cached goods-Create a Jedis tool class to connect to redis

Flow chart of using redis:

Insert picture description here

A mind map to realize the classification of cached goods:

Insert picture description here

  1. The browser sends the request, and the server receives the request and hands it to the queryAll() method of the CategroySerivce class to process the query data
  2. When querying redis for the first time, if there is no data (json format), call CategoryDao to search in the database (MySQL), get the collection List product classification collection, and then first return to CategorySrvice, let it convert the List data into json and cache it in redis, and at the same time The json data is returned to the server.
  3. For the second query, get the product classification in json data format directly from redis, then convert the json into a List, and display it on the browser.

Case realization

1. Writing test classes

//第一步:测试开发CategoryService
public class TestCategoryService {
    
    
    @Test
    public void test01() throws Exception {
    
    
        //1. 创建业务类对象
        CategoryService categoryService = new CategoryService();
        //2. 查询所有分类集合
        List<Category> list = categoryService.queryAll();
        //3. 循环遍历输出
        for(Category category:list){
    
    
            System.out.println(category);
        }
    }
}

2. Bean (Category) to write product classification

public class Category {
    
    
    private int cid;		//编号
    private String cname;	//名称
   //省略setter和getter
}

3. Create a properties file (jedis.properties) to store key-value pairs

maxTotal=50
maxIdle=15
url=localhost
port=6379

4. Create the Jedis tool class, connect to redis, read the key-value pair configuration of the propties file

//使用ResourceBundle读.propties文件
public class JedisUtils {
    
    
    //单例模式 静态代码块只执行一次,因为创建会很消耗性能
    private static JedisPool pool = null;
    //1. 创建一个连接池   静态代码在项目中,如果被使用只会加载一次
    static{
    
    
        //1.1 通过ResourceBundle读取properties文件 jedis.properties
        ResourceBundle bundle = ResourceBundle.getBundle("jedis");

        //获取参数
        String maxTotal = bundle.getString("maxTotal");
        String maxIdle = bundle.getString("maxIdle");
        String url = bundle.getString("url");
        String port = bundle.getString("port");

        //1.2创建连接池
        //创建连接池的配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        //设置最大连接数
        config.setMaxTotal(Integer.parseInt(maxTotal));
        //设置空闲连接数
        config.setMaxIdle(Integer.parseInt(maxIdle));

        //2:创建连接池
        pool = new JedisPool(config, url, Integer.parseInt(port));
    }

    //2。 对外提供一个获取连接的方法
    public static Jedis getJedis(){
    
    
        return  pool.getResource();
    }

    //3。 提供释放资源的方法
    public static void close(Jedis jedis){
    
    
        if(jedis != null) {
    
    
            jedis.close();
        }
    }
}

5. Write the service layer (CategoryService)

public class CategoryService {
    
    
    //调用dao层查询数据
    CategoryDao dao = new CategoryDao();
    //jackson 的 ObjectMapper类3  用来将数据与json格式相互转换
    ObjectMapper objectMapper = new ObjectMapper();
    public List<Category> queryAll() throws IOException {
    
    
        //1. 先访问redis,有数据就返回 JedisUtils  数据格式:Map<Srting,String>
        //  获取redis连接
         Jedis redis = JedisUtils.getJedis();
        //  查找redis缓存中的数据
        String json = redis.get("categoryList");
        if(json == null){
    
    //2. 如果没有数据就查询数据库(MySQL),缓存到redis
            System.out.println("(第一次查询) redis中没有数据,去查找数据库的数据");
            List<Category> categoryList = dao.findAll();
            //缓存  将查找到的list集合转换成json数据格式,缓存到redis上
            //通过ObjectMapper对象,转list数据格式转化成json数据格式
            String categoryListJson =  objectMapper.writeValueAsString(categoryList);
			System.out.println("查找到的categoryList的json数据是:");
            System.out.println(categoryListJson);

            redis.set("categoryList",categoryListJson);
            return categoryList;
        }else{
    
    //json ! =null 在redis中查询到了数据
            System.out.println("非第一次查询,数据缓存到redis中,redis有数据,直接从内存中返回,速度快");
            //将json转成对象   参1 json数据  参2 TypeReference
            List<Category> categoryList = objectMapper.readValue(json,new TypeReference<List<Category>>(){
    
    });
            return categoryList;
        }

    }
}

6. Write dao layer

public class CategoryDao {
    
    
    public List<Category> findAll() {
    
    
        //1:创建集合
        List<Category> categoryList = new ArrayList<>();
        //使用循环模拟数据,以后使用mybatis来查数据
        for (int i = 0; i < 10; i++) {
    
    
            categoryList.add(new Category(i,"菜单名" + i));
        }
        return categoryList;
    }
}

7. Test TestCategoryService to see if the logic is correct

(The redis connected here is the local localhost, the reids server needs to be turned on redis-server.exe, otherwise a connection error will be reported)

First query test

(First query) There is no data in redis, to find the data in the database.
The json data of the categoryList found is:
[{"cid":0,"cname":"menu name0"},{"cid":1 ,"Cname":"menu name 1"},{"cid":2,"cname":"menu name 2"},{"cid":3,"cname":"menu name 3"},{" cid":4,"cname":"menu name 4"},{"cid":5,"cname":"menu name 5"},{"cid":6,"cname":"menu name 6" },{"Cid":7,"cname":"menu name 7"},{"cid":8,"cname":"menu name 8"},{"cid":9,"cname":" Menu name 9”}]
Category{cid=0, cname='menu name 0'}
Category{cid=1, cname='menu name 1'}
Category{cid=2, cname='menu name 2'}
Category{ cid=3, cname='menu name 3'}
Category{cid=4, cname='menu name 4'}
Category{cid=5, cname='menu name 5'}
Category{cid=6, cname='menu Name 6'}
Category{cid=7, cname='menu name 7'}
Category{cid=8, cname='menu name 8'}
Category{cid=9, cname='menu name 9'}

Second/third query data (any number of times other than the first search)

Not the first query, the data is cached in redis, redis has data, and returns directly from the memory, fast
Category{cid=0, cname='menu name 0'}
Category{cid=1, cname='menu name 1 '}
Category{cid=2, cname='menu name 2'}
Category{cid=3, cname='menu name 3'}
Category{cid=4, cname='menu name 4'}
Category{cid=5, cname='menu name 5'}
Category{cid=6, cname='menu name 6'}
Category{cid=7, cname='menu name 7'}
Category{cid=8, cname='menu name 8'}
Category{cid=9, cname='menu name 9'}

From the results, we can know that there is no error in the business logic, and then you can write the page

8. Write page Servlet display (just write the test type copy and modify)

@WebServlet("/CategoryListServlet")
public class CategoryListServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //1. 创建业务类对象
        CategoryService categoryService = new CategoryService();

        //2. 查询分类集合
        List<Category> categoryList = categoryService.queryAll();

        //3. 请求转发
        request.setAttribute("categoryList",categoryList);
        request.getRequestDispatcher("categoryList.jsp").forward(request,response);

    }
}

9. Filter to prevent messy codes

//拦截所有,进行编码设置
@WebFilter("/*")
public class EncodingFilter implements Filter {
    
    
    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);//放行
    }
}

10. Write jsp pages

<%-- isELIgnored="false 开启el表达式--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 <html>
<head>
    <title>categoryList商品类型列表</title>
</head>
<body>


        <c:if test="${empty categoryList}">
            商品类型是空的哟
        </c:if>
        <c:if test="${!empty categoryList}">
            <table border="1" cellpadding="0" cellspacing="0">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>商品类型名称</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach items="${categoryList}" var="category" varStatus="vs">

                    <tr>
                        <td>${vs.count}</td>
                        <td>${category.cname}</td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </c:if>
</body>
</html>

11. Required jar package

Insert picture description here

12. Run results

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/108740426