CacheFactory.java 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package com.primeton.dgs.kernel.core.cache.impl;
  2. import com.primeton.dgs.kernel.core.cache.ICache;
  3. import org.apache.commons.lang.StringUtils;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.FactoryBean;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;
  9. import java.io.IOException;
  10. import java.net.InetSocketAddress;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.Optional;
  14. import java.util.Properties;
  15. /**
  16. * <pre>
  17. *
  18. * Created by zhaopx.
  19. * User: zhaopx
  20. * Date: 2019/11/14
  21. * Time: 14:22
  22. *
  23. * </pre>
  24. *
  25. * @author zhaopx
  26. */
  27. public class CacheFactory implements FactoryBean {
  28. /**
  29. * logger
  30. */
  31. private static Logger logger = LoggerFactory.getLogger(CacheFactory.class);
  32. /**
  33. * 配置
  34. */
  35. private final Properties config;
  36. /**
  37. * Cache
  38. */
  39. private final ICache cache;
  40. /**
  41. * 默认是 ehcache
  42. * @param config
  43. */
  44. public CacheFactory(Properties config) {
  45. this(config == null ? "ehcache" : config.getProperty("type", "ehcache"), config);
  46. }
  47. public CacheFactory(String cacheType, Properties props) {
  48. this.config = Optional.ofNullable(props).orElse(new Properties());
  49. if(StringUtils.isBlank(cacheType) || "mem".equalsIgnoreCase(cacheType) ||
  50. "ehcache".equalsIgnoreCase(cacheType)) {
  51. logger.info("use ehcache.");
  52. this.cache = initEhcache();
  53. } else if("redis".equalsIgnoreCase(cacheType)) {
  54. String host = this.config.getProperty("host");
  55. if(StringUtils.isBlank(host)) {
  56. throw new IllegalArgumentException("redis cache host must not be blank.");
  57. }
  58. int port = Integer.parseInt(this.config.getProperty("port", "3306"));
  59. int db = Integer.parseInt(this.config.getProperty("db", "0"));
  60. logger.info("use redis cache {}:{}/{}", host, port, db);
  61. this.cache = initRedisCache(host, port, db);
  62. } else if("memcache".equalsIgnoreCase(cacheType)) {
  63. String address = this.config.getProperty("address");
  64. if(StringUtils.isBlank(address)) {
  65. throw new IllegalArgumentException("memcache address must not be blank. Usage: host1:port,host2:port");
  66. }
  67. logger.info("use memcache address {}", address);
  68. this.cache = initMemCache(address);
  69. } else {
  70. throw new IllegalArgumentException("unknown cache type " + cacheType);
  71. }
  72. }
  73. /**
  74. * 初始化 MemCache
  75. * @return
  76. */
  77. private ICache initMemCache(String hosts) {
  78. List<InetSocketAddress> addresses = new ArrayList<>();
  79. String[] addrs = hosts.split(",");
  80. for (String addr : addrs) {
  81. String[] hostAndPort = addr.split(":");
  82. addresses.add(new InetSocketAddress(StringUtils.trim(hostAndPort[0]),
  83. Integer.parseInt(StringUtils.trim(hostAndPort[1]))));
  84. }
  85. net.rubyeye.xmemcached.XMemcachedClientBuilder clientBuilder =
  86. new net.rubyeye.xmemcached.XMemcachedClientBuilder(addresses);
  87. clientBuilder.setConnectionPoolSize(2);
  88. clientBuilder.setCommandFactory(new net.rubyeye.xmemcached.command.TextCommandFactory());
  89. clientBuilder.setSessionLocator(new net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator());
  90. clientBuilder.setTranscoder(new net.rubyeye.xmemcached.transcoders.SerializingTranscoder());
  91. try {
  92. return new Memcached(clientBuilder.build());
  93. } catch (IOException e) {
  94. throw new IllegalStateException(e);
  95. }
  96. }
  97. /**
  98. * 初始化 Redis 客户端
  99. * @param host
  100. * @param port
  101. * @param db
  102. * @return
  103. */
  104. private ICache initRedisCache(String host, int port, int db) {
  105. return new Redised(host, port, db);
  106. }
  107. /**
  108. * 初始化 EHCache 客户端
  109. * @return
  110. */
  111. private ICache initEhcache() {
  112. return new Ehcache();
  113. }
  114. @Override
  115. public Object getObject() throws Exception {
  116. return cache;
  117. }
  118. @Override
  119. public Class getObjectType() {
  120. return ICache.class;
  121. }
  122. @Override
  123. public boolean isSingleton() {
  124. return true;
  125. }
  126. public static void main(String[] args) {
  127. ApplicationContext context = new ClassPathXmlApplicationContext("/spring/corebean/context-cache.xml");
  128. ICache cache = (ICache)context.getBean("cache");
  129. System.out.println(cache.size());
  130. }
  131. }