package com.panda.core.db.impl; import com.panda.core.log.log.util.Tools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 缓存服务 * Created by Lovell on 16/6/16. */ public class CacheService { private static Logger logger = LoggerFactory.getLogger(CacheService.class); private static String CACHE_CONFIG_FILE = "/redis.properties"; // 缓存过期时间 private int rdExpiredtime = 0; // 缓存地址 private String rdUrl = null; // 端口 private short rdPort = 0; // 锁超时最长时间 private int rdLocktimeout = 0; // redis连接超时时间 private int rdConnTimeout = 0; // redis缓冲池 private JedisPool jedisPool = null; private static CacheService cacheService; public static CacheService getInstance() { if (cacheService == null) { cacheService = new CacheService(); } return cacheService; } public void setCacheConfigFilePathName(final String path) { if (path.charAt(0) == '/') { CACHE_CONFIG_FILE = path; } else { CACHE_CONFIG_FILE = "/" + path; } } /** * 连接redis */ public void start() throws IOException { Properties properties = new Properties(); String strPath = Tools.getPath(); File dbFile = new File(strPath + CACHE_CONFIG_FILE); InputStream inputStream = new FileInputStream(dbFile); // 获取Resource路径的配置文件 // InputStream inputStream = CacheService.class.getClass().getResourceAsStream(CACHE_CONFIG_FILE); properties.load(inputStream); rdExpiredtime = Integer.valueOf(properties.getProperty("redis.expiredTime")); rdUrl = properties.getProperty("redis.url"); rdPort = Short.valueOf(properties.getProperty("redis.port")); rdLocktimeout = Integer.valueOf(properties.getProperty("redis.lockTimeout")); JedisPoolConfig config = new JedisPoolConfig(); jedisPool = new JedisPool(config, rdUrl, rdPort, rdConnTimeout); logger.info("redis client start ok"); getJedis(); } /** * 关闭缓存 */ public void stop() throws IOException { if (jedisPool != null) { jedisPool.destroy(); } } public JedisPool getJedisPool() { return jedisPool; } /** * 测试连接Redis服务器 * @return */ public Jedis getJedis() { try { return jedisPool.getResource(); } catch (Exception e) { logger.error("redis server is not running"); } return null; } /** * 缓冲超时 * @return */ public int getCacheExpiredTime() { return rdExpiredtime; } /** * 锁超时时间 * @return */ public int getCacheLocktimeout() { return rdLocktimeout; } }
Java Redis缓存服务类
最新推荐文章于 2022-07-12 21:25:52 发布