综合案例使用Redis缓存
思路分析
实现代码
CategoryServlet
//创建业务类对象
CategoryService service = new CategoryService();
//查询分类集合
List<Category> categories = service.queryAll();
//请求转发
request.setAttribute("list",categories);
request.getRequestDispatcher("list.jsp").forward(request,response);
Category
private int cid;
private String cname;
public Category() {
}
public Category(int cid, String cname) {
this.cid = cid;
this.cname = cname;
}
CategoryService
public class CategoryService {
CategoryDao categoryDao = new CategoryDao();
ObjectMapper objectMapper = new ObjectMapper();
public List<Category> queryAll() throws IOException {
//queryAll的逻辑
//1.先访问Redis,有数据据返回,jedisUtils Map<String,String>
//获取连接
Jedis redis = JedisUtils.getRedis();
String json = redis.get("list");
if (json == null){
//没有数据就查询数据,进行缓存,方便下次使用
List<Category> daoAll = categoryDao.findAll();
String value = objectMapper.writeValueAsString(daoAll);
redis.set("list",value);
return daoAll;
}else{
//json != null
List<Category> readValue = objectMapper.readValue(json, new TypeReference<List<Category>>() {
});
return readValue;
}
}
}
CategoryDao
public List<Category> findAll() {
//创建结合
List<Category> list = new ArrayList<>();
//使用循环模拟数据
for (int i=0;i<10;i++){
list.add(new Category(i,"分类名"+i));
}
return list;
}
CategoryFilter
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);
}
JedisUtils
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();
}
}
}
list.jsp
<%@ 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>Title</title>
</head>
<body>
<c:forEach items="${list}" var="item">
<div>${item.cname}</div>
</c:forEach>
</body>
</html>