Cache technology in JAVA ehcacha

Cache technology in JAVA ehcacha

1. Basic introduction to Ehcacha

EhCache is a pure Java in-process caching framework with fast and lean features. It is the default CacheProvider in Hibernate. The specific introduction can be found in Baidu Encyclopedia ( https://baike.baidu.com/item/ehcache/6036099?fr=aladdin ). In order to provide the performance of the system, reduce the pressure on the server, and reduce the access to the database is the main part of the optimization system. In our actual project, we can deal with those data that do not change frequently (also stored in the database). ) reduces access to the database and can be cached locally after the first request. At this time, a caching technology is needed. Of course, there are many caching technologies, and here's an introduction to Ecacha.

2. Environmental preparation

jar package, configuration file: This program will give the program source code (including jar package) at the end;
it should be noted that: the program here creates a basic dynamic web page for example introduction, and the configuration file is placed in the src directory. .

3. Code Analysis

front end:

<div align="center">
<p>信息状况:${msg }</p>
<form action="${pageContext.request.contextPath }/info" method="get">
<input type="submit" value="查看数据库的数据" />

</form>
<table border="0">
     <c:forEach items="${list}" var="user">
    <tr>
        <td>数据库中的用户名:</td><td>${user.userName} </td>
         <td>数据中的用户邮箱</td><td>${user.email}</td>
    </tr>
 </c:forEach>

</table>
</div>

rear end:

public class InfoServlet extends HttpServlet {

    private static JDBCUtil JDBCUtile = new JDBCUtil();
    private static Connection conn;
    private static PreparedStatement ps;
    private static ResultSet rs;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.创建缓存管理器
        CacheManager cm=CacheManager.create(InfoServlet.class.getClassLoader().getResourceAsStream("ehcache.xml"));
        //2.获取存的缓存
        Cache cache = cm.getCache("user");
        //3.通过缓存获取数据,将cache看作是一个map集合
        Element element = cache.get("list");

        List<User> list=new ArrayList<User>();

        //4.判断数据
        if(element==null) {
            //从数据库获取
            try {
                conn = JDBCUtile.getConn();
                String sql = "select * from user";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    User user = new User();
                    user.setId(rs.getString("id"));
                    user.setUserName(rs.getString("userName"));
                    user.setEmail(rs.getString("email"));
                    user.setPassword(rs.getString("password"));
                    user.setSex(rs.getInt("sex"));
                    user.setPhone(rs.getString("phone"));
                    list.add(user);
                }
                JDBCUtile.closeConn(rs, ps, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //将list放入到缓存
            cache.put(new Element("list", list));
            request.setAttribute("list", list);
            request.setAttribute("msg", "缓存中无数据");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            }else {
                //直接返回缓存的数据
                list =(List<User>) element.getObjectValue() ;
                request.setAttribute("list", list);
                request.setAttribute("msg", "缓存中有数据");
                request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

For other configurations, please refer to the source code

4. Running results

write picture description here
write picture description here
write picture description here

5. Summary

Program source code: link: https://pan.baidu.com/s/16opqzhrzjKWmh31R1Pgfpw Password: vnhv
For the specific use of ehcacha, readers can improve it according to their own situation, and this blog only introduces this caching mechanism in this way.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326052023&siteId=291194637