1.导入jedis和池子的jar包
https://mvnrepository.com/artifact/org.apache.commons/commons-pool2/2.3
https://mvnrepository.com/artifact/redis.clients/jedis/2.7.0
2.导入工具类
package com.itheima.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;public class JedisPoolUtils {
private static JedisPool pool = null;
static{
//加载配置文件
InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("redis.properties");
Properties pro = new Properties();
try {
pro.load(in);
} catch (IOException e) {
e.printStackTrace();
}
//获得池子对象
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));//最大闲置个数
poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));//最小闲置个数
poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));//最大连接数
pool = new JedisPool(poolConfig,pro.getProperty("redis.url") , Integer.parseInt(pro.get("redis.port").toString()));
}//获得jedis资源的方法
public static Jedis getJedis(){
return pool.getResource();
}
public static void main(String[] args) {
Jedis jedis = getJedis();
System.out.println(jedis.get("xxx"));
}
}
3.导入配置文件
redis.maxIdle=30
redis.minIdle=10
redis.maxTotal=100
redis.url=localhost
redis.port=6379
4. 编写代码
package com.itheima.web.servlet;
import java.io.IOException;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.google.gson.Gson;
import com.itheima.domain.Category;
import com.itheima.service.ProductService;
import com.itheima.utils.JedisPoolUtils;import redis.clients.jedis.Jedis;
public class CategoryListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ProductService service = new ProductService();
//先从缓存中查询categoryList 如果有直接使用 没有在从数据库中查询 存到缓存中
//1、获得jedis对象 连接redis数据库
Jedis jedis = JedisPoolUtils.getJedis();
String categoryListJson = jedis.get("categoryListJson");
//2、判断categoryListJson是否为空
if(categoryListJson==null){
System.out.println("缓存没有数据 查询数据库");
//准备分类数据
List<Category> categoryList = service.findAllCategory();
Gson gson = new Gson();
categoryListJson = gson.toJson(categoryList);
jedis.set("categoryListJson", categoryListJson);
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(categoryListJson);
}protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}