標籤:串連 tco private dal pool 資料庫連接 redis exception tcl
需要用到的jar:
commons-pool2-2.3.jar
jedis-2.7.0.jar
JedisPoolConfig的設定檔redis.properties
redis.maxIdle=30redis.minIdle=10redis.maxTotal=100redis.url=localhostredis.port=6379
redis資料庫連接的串連池工具類JedisPoolUtils
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")); }}
redis使用:
//先從緩衝中查詢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); //將查詢出來的資料放到redis資料庫中 jedis.set("categoryListJson", categoryListJson); }response.setContentType("text/html;charset=UTF-8");response.getWriter().write(categoryListJson);
使用redis的緩衝功能 (windows 版redis)