依赖包:
<!-- xmemcached --> <dependency> <groupId>com.googlecode.xmemcached</groupId> <artifactId>xmemcached</artifactId> <version>2.0.0</version> </dependency>
配置:
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "meihaocloud.cache.memcache") public class MemcacheProp { private String server; private String weight; private String poolSize; private String connectTimeout; private String opTimeout; public String getServer() { return server; } public void setServer(String server) { this.server = server; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getPoolSize() { return poolSize; } public void setPoolSize(String poolSize) { this.poolSize = poolSize; } public String getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(String connectTimeout) { this.connectTimeout = connectTimeout; } public String getOpTimeout() { return opTimeout; } public void setOpTimeout(String opTimeout) { this.opTimeout = opTimeout; } }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.meihaocloud.common.cache.icache.ICache; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.buffer.SimpleBufferAllocator; import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator; import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; import net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean; @SuppressWarnings("deprecation") @Configuration public class MemcacheStarterAutoConfigure { @Autowired private MemcacheProp memcacheProp; //=============memcache=========================================================================== @Bean("icache") @ConditionalOnMissingBean public ICache cache(MemcachedClient MemcachedClient) throws Exception { MemcachedCache cache = new MemcachedCache(); cache.setMemcachedClient(MemcachedClient); return cache; } @Bean @ConditionalOnMissingBean public MemcachedClient memcachedClient() throws Exception { XMemcachedClientFactoryBean facBean = xmemcachedClientFactoryBean(); return (MemcachedClient) facBean.getObject(); } @Bean(destroyMethod = "shutdown") @ConditionalOnMissingBean public XMemcachedClientFactoryBean xmemcachedClientFactoryBean() { XMemcachedClientFactoryBean facBean = new XMemcachedClientFactoryBean(); StringBuffer servers = new StringBuffer(); String[] serv = memcacheProp.getServer().split(","); for (int i = 0; i < serv.length; i++) { servers.append(serv[i]).append(" "); } facBean.setServers(servers.toString().trim()); String[] we = memcacheProp.getWeight().split(","); List<Integer> weights = new ArrayList<Integer>(); for (int i = 0; i < we.length; i++) { weights.add(Integer.parseInt(we[i].trim())); } facBean.setWeights(weights); if (memcacheProp.getPoolSize() != null && !"".equals(memcacheProp.getPoolSize().trim())) { facBean.setConnectionPoolSize(Integer.parseInt(memcacheProp.getPoolSize().trim())); } if (memcacheProp.getConnectTimeout() != null && !"".equals(memcacheProp.getConnectTimeout().trim())) { facBean.setConnectTimeout(Long.parseLong(memcacheProp.getConnectTimeout().trim())); } if (memcacheProp.getOpTimeout() != null && !"".equals(memcacheProp.getOpTimeout().trim())) { facBean.setOpTimeout(Long.parseLong(memcacheProp.getOpTimeout().trim())); } facBean.setSessionLocator(new KetamaMemcachedSessionLocator()); facBean.setTranscoder(new SerializingTranscoder()); facBean.setBufferAllocator(new SimpleBufferAllocator()); return facBean; } }
application.properties
#主集群
meihaocloud.cache.memcache.server=192.168.8.111:12000,192.168.8.111:12001
#权重
meihaocloud.cache.memcache.weight=1,1
#连接池
meihaocloud.cache.memcache.poolSize=10
#连接超时时间
meihaocloud.cache.memcache.connectTimeout=3000
#操作超时时间
meihaocloud.cache.memcache.opTimeout=5000
Memcache
import com.meihaocloud.common.cache.icache.ICache; import net.rubyeye.xmemcached.MemcachedClient; /** * @className MemCache.java * @date 2018年4月22日 下午10:33:04 * @doc memcached 作缓存 , memcahce不能实现高可用的缓存,每个key在进行hash一致性算后,保存到指定的memcached里面, * 集群里其他memcached时没有保存这个key的 。通过代码实现一个备用集群。 */ public class MemcachedCache implements ICache { private MemcachedClient memcachedClient; public MemcachedClient getMemcachedClient() { return memcachedClient; } public void setMemcachedClient(MemcachedClient memcachedClient) { this.memcachedClient = memcachedClient; } /** * @param key * @param exp * 单位S(秒) * @param value * @return */ @Override public Object get(String key) { Object object = null; try { object = memcachedClient.get(key); } catch (Exception e) { e.printStackTrace(); } return object; } /** * @param key * @param exp * 单位S(秒) * @param value * @return */ @Override public boolean add(String key, Object value ,int exp) { try { if (exp <= 0) { exp = defaultExp; } return memcachedClient.set(key, exp, value); } catch (Exception e) { e.printStackTrace(); } return false; } @Override public boolean add(String key, Object value) { try { return memcachedClient.set(key, defaultExp, value); } catch (Exception e) { e.printStackTrace(); } return false; } /** * @param key * @param exp * 单位S(秒) * @param value * @return */ @Override public void remove(String key) { try { memcachedClient.delete(key); } catch (Exception e) { e.printStackTrace(); } } @Override public void clear() { try { memcachedClient.flushAll(); } catch (Exception e) { e.printStackTrace(); } } @Override public void removeByRegex(String regex) { // memcache不自带查询所有key的方法,网上有解决办法,感觉效率较低,暂不使用 。直接删除key try { memcachedClient.delete(regex); } catch (Exception e) { e.printStackTrace(); } } }
注入Bean即可使用:
@Autowired
private ICache icache ;
老版本Spring整合方式:
applicationContext-memcached.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <bean name="cache" class="com.meihaocloud.common.cache.memcached.MemcachedCache"> <property name="memcachedClient" ref="memcachedClient" /> </bean> <bean name="memcachedClient" destroy-method="shutdown" class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean"> <property name="servers"> <value>192.168.8.111:12000 192.168.8.111:12001</value> </property><!-- 192.168.8.111:12000 192.168.8.111:12001 192.168.8.131:12000 192.168.8.131:12001 --> <property name="weights"> <list> <value>1</value> <value>1</value> <!-- <value>1</value> --> <!-- <value>1</value> --> </list> </property> <property name="connectionPoolSize" value="5" /> <property name="opTimeout" value="3000" /> <property name="sessionLocator"> <bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" /> </property> <property name="transcoder"> <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" /> </property> <property name="bufferAllocator"> <bean class="net.rubyeye.xmemcached.buffer.SimpleBufferAllocator" /> </property> </bean> </beans>