package com.primeton.dgs.kernel.core.cache.impl; import com.primeton.dgs.kernel.core.cache.ICache; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Properties; /** *
* * Created by zhaopx. * User: zhaopx * Date: 2019/11/14 * Time: 14:22 * ** * @author zhaopx */ public class CacheFactory implements FactoryBean { /** * logger */ private static Logger logger = LoggerFactory.getLogger(CacheFactory.class); /** * 配置 */ private final Properties config; /** * Cache */ private final ICache cache; /** * 默认是 ehcache * @param config */ public CacheFactory(Properties config) { this(config == null ? "ehcache" : config.getProperty("type", "ehcache"), config); } public CacheFactory(String cacheType, Properties props) { this.config = Optional.ofNullable(props).orElse(new Properties()); if(StringUtils.isBlank(cacheType) || "mem".equalsIgnoreCase(cacheType) || "ehcache".equalsIgnoreCase(cacheType)) { logger.info("use ehcache."); this.cache = initEhcache(); } else if("redis".equalsIgnoreCase(cacheType)) { String host = this.config.getProperty("host"); if(StringUtils.isBlank(host)) { throw new IllegalArgumentException("redis cache host must not be blank."); } int port = Integer.parseInt(this.config.getProperty("port", "3306")); int db = Integer.parseInt(this.config.getProperty("db", "0")); logger.info("use redis cache {}:{}/{}", host, port, db); this.cache = initRedisCache(host, port, db); } else if("memcache".equalsIgnoreCase(cacheType)) { String address = this.config.getProperty("address"); if(StringUtils.isBlank(address)) { throw new IllegalArgumentException("memcache address must not be blank. Usage: host1:port,host2:port"); } logger.info("use memcache address {}", address); this.cache = initMemCache(address); } else { throw new IllegalArgumentException("unknown cache type " + cacheType); } } /** * 初始化 MemCache * @return */ private ICache initMemCache(String hosts) { List