memcached(九)客户端高级-Java
简介
目前常用的Java客户端有3种。
MemcachedClientspymemcachedxmemcached
,MemcachedClient:其中笔者亲测,在高并发的时候,容易报异常,Out Of Memory。
spy:的性能比xmemcached略差。
xmemcached:虽然是国产,但是首选,性能和稳定性超强。
xmemcached
代码解析
设置连接池和权重
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("10.11.155.26:11211 10.11.155.41:11211 10.10.76.31:11211 10.10.76.35:11211"), new int[] { 1, 1, 1, 1 }); // 设置连接池大小,即客户端个数 builder.setConnectionPoolSize(50);
memcachedClient.beginWithNamespace("sx"); //命名空间
try { MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddressMap("10.10.160.153:11211,10.10.160.153:11212")); builder.setSessionLocator(new KetamaMemcachedSessionLocator()); builder.setFailureMode(true); // 在此模式下,某个节点挂掉的情况下,往这个节点的请求都将直接抛出MemcachedException的异常。 MemcachedClient client = builder.build(); } catch (Exception e) { System.out.println("自定义异常"); e.printStackTrace(); }
memcachedClient.addStateListener(new MemcachedClientStateListener());//此处用的是一个匿名类
<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"><!-- 配置文件 --><bean id="configproperties" ref="configproperties" /></bean><!-- memcached初始化 --><bean id="builder" factory-method="getAddresses"><constructor-arg value="${memcached.host}" /></bean></constructor-arg></bean><bean id="memcachedClient" factory-bean="builder" factory-method="build" destroy-method="shutdown" /></beans>