redis缓存服务器进行导航条缓存并显示在前台

工具类:JedisPoolUtils.java

package com.yinhe.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();
}
//获得池子对象(redis数据库)
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"));
}
}

配置文件:redis.properties

redis.maxIdle=30
redis.minIdle=10
redis.maxTotal=100
redis.url=localhost
redis.port=6379

实体类:Category.java

package com.yinhe.bean;
public class Category {
private String cid;
private String cname;
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
}

Dao层和service层

 

public static List findAllCategories() throws SQLException{
String sql = "select * from category";
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
return qr.query(sql, new BeanListHandler(Category.class));
}

//查询所有的类型
public List findAllCategories(){
try {
return CategoryDao.findAllCategories();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

Servlet层:CategoryServlet.java

// 处理ajax
public void findAllCategory(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

Jedis jedis = JedisPoolUtils.getJedis();
// 获取json_list
String json_list = jedis.get("json_list");
if (json_list == null) {
List list = cs.findAllCategories();
json_list = JSONArray.fromObject(list).toString();
// 缓存json_list
jedis.set("json_list", json_list);
// del删除
// jedis.del("json_list");
}

response.getWriter().println(json_list);

前台ajax请求

redis缓存服务器进行导航条缓存并显示在前台_第1张图片

你可能感兴趣的:(Redis)