前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Memcached三种客户端的使用

Memcached三种客户端的使用

作者头像
一觉睡到小时候
发布2019-07-03 18:04:13
1.1K0
发布2019-07-03 18:04:13
举报
文章被收录于专栏:国产程序员

第一种 memcached 第二种 spyMemcached 第三种 XMemcached

三者差异与性能比对

com.danga 包下的 memcached 第一种出来的版本很早,资料也比较全。网上也有很多解释以及例子,但如今实际项目使用中几乎不用它,大概是性能与迸发低于后两种。 xmemcached与spymemcached xmemcached比spymemcached有更好的性能表现,在get、set、delete、multi-gets等操作的测试中都远远超过或者接近spymemcached。 xmemcached在win32和linux两个平台上都有极佳的性能表现。 xmemcached支持动态地添加或者移除memcached server,可以通过编程或者JMX来做到。 xmemcached支持JMX,可以通过jmx调整性能参数、添加/移除memcached节点、查看统计。 xmemcached有客户端统计,可以统计xmemcached客户端的各种操作的总次数。 xmemcached允许调整更多的网络层参数和优化选项。 xmemcached暂未支持二进制协议,计划在1.2版本中实现。 xmemcached的API模型是同步的,而spymemcached的API模型是异步模型,同步模型对应用编程来说更容易使用和直观。 xmemcached的序列化机制,是使用了spymemcached的序列化机制,并做了部分改造。

三者具体使用

第一种
1.配置文件memcached.xml
代码语言:javascript
复制
    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans.xsd">  

        <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"  
            factory-method="getInstance" init-method="initialize">  
            <constructor-arg>  
                <value>neeaMemcachedPool</value>  
            </constructor-arg>  
            <!-- 服务器连接地址 -->  
            <property name="servers">  
                <list>  
                    <value>127.0.0.1:11211</value>  
                </list>  
            </property>  

            <!-- 初始化连接数 -->  
            <property name="initConn" value="20" />  
            <!-- 最小连接数 -->  
            <property name="minConn" value="10" />  
            <!-- 最大连接数 -->  
            <property name="maxConn" value="50" />  
            <!-- 设置tcp连接参数   nagle演算法为false(具体是什么不知道)-->  
            <property name="nagle" value="false" />  
            <!-- 连接超时时间 -->  
            <property name="socketTO" value="3000" />  
        </bean>  

        <bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient">  
            <constructor-arg>  
                <value>neeaMemcachedPool</value>  
            </constructor-arg>  
        </bean>  

        <!-- 注入自己写的类 -->  
        <bean id="memcachedUtils" class="com.sss.comm.MemcachedUtils" />  
    </beans><span style="">   </span>  
2.封装的memcached的使用类
代码语言:javascript
复制
import java.util.Date;  

import org.apache.commons.lang3.StringUtils;  
import org.slf4j.LoggerFactory;  
import org.springframework.beans.factory.annotation.Autowired;  

import com.danga.MemCached.MemCachedClient;  

public class MemcachedUtils {  

    protected org.slf4j.Logger logger = LoggerFactory  
            .getLogger(this.getClass());  

    @Autowired  
    private MemCachedClient memcachedClient;  

    /*** 
     * 添加缓存 
     *  
     * @param key 
     * @param value 
     * @param expiry 
     *            超时时间(单位:分钟) 
     * @throws Exception 
     */  
    public void addCache(String key, Object value, int expiry) throws Exception {  

        if (StringUtils.isEmpty(key) || value == null) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        // 时间换成分钟  
        Date date = new Date();  
        date.setTime(date.getTime() + expiry * 60 * 1000);  
        boolean isSuc = memcachedClient.set(key, value, date);  
        if (!isSuc) {  
            throw new IllegalStateException("缓存存储失败!");  
        }  
    }  

    /*** 
     * 查找 
     *  
     * @param key 
     *            键值 
     * @return 
     * @throws Exception 
     */  
    public Object findCache(String key) throws Exception {  
        if (StringUtils.isEmpty(key)) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        return memcachedClient.get(key);  
    }  

    /*** 
     * 删除 
     *  
     * @param key 
     *            键值 
     * @throws Exception 
     */  
    public void deleteCache(String key) throws Exception {  
        if (StringUtils.isEmpty(key)) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        memcachedClient.delete(key);  
    }  

}  
3.使用方式

获取到MemcachedUtils类调用其方法即可。

第二种
1.附上与maven集成的依赖
代码语言:javascript
复制
<dependency>  
    <groupId>spy</groupId>  
    <artifactId>spymemcached</artifactId>  
    <version>2.8.12</version>  
</dependency><span style="">    
2.配置文件 spy-memcached.xml
代码语言:javascript
复制
    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans.xsd">  

       <bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">    
        <property name="servers" value="127.0.0.1:11211"/>    
        <property name="protocol" value="BINARY"/>    
        <property name="transcoder">    
          <bean class="net.spy.memcached.transcoders.SerializingTranscoder">    
            <property name="compressionThreshold" value="1024"/>    
          </bean>    
        </property>    
        <property name="opTimeout" value="1000"/>    
        <property name="timeoutExceptionThreshold" value="1998"/>    
         <property name="hashAlg" value="KETAMA_HASH"/>   
        <property name="locatorType" value="CONSISTENT"/>     
        <property name="failureMode" value="Redistribute"/>    
        <property name="useNagleAlgorithm" value="false"/>    
      </bean>    

        <!-- 注入自己写的类 -->  
        <bean id="memcachedUtils" class="com.sss.util.MemcachedUtils" />  
    </beans>  
3.封装的memcached使用类

注:该方式与第一种类似,只是在set方法的时候,传入参数顺序调换。缓存时间需注意,若memcached的服务端装在windows上,可能会出现运行错误。

代码语言:javascript
复制
import net.spy.memcached.MemcachedClient;  
import org.apache.commons.lang3.StringUtils;  
import org.slf4j.LoggerFactory;  
import org.springframework.beans.factory.annotation.Autowired;  

public class MemcachedUtils {  

    protected org.slf4j.Logger logger = LoggerFactory  
            .getLogger(this.getClass());  
    @Autowired  
    private MemcachedClient memcachedClient;  

    /*** 
     * 添加缓存 
     *  
     * @param key 
     * @param value 
     * @param expiry 
     *            超时时间(单位:分钟) 
     * @throws Exception 
     */  
    public void addCache(String key, Object value, int expiry) throws Exception {  

        if (StringUtils.isEmpty(key) || value == null) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        //Date date = new Date();  
        //date.setTime(date.getTime() + expiry * 60 * 1000);  
        memcachedClient.set(key, expiry, value);  

    }  

    public Object findCache(String key) throws Exception {  
        if (StringUtils.isEmpty(key)) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        return memcachedClient.get(key);  
    }  

    public void deleteCache(String key) throws Exception {  
        if (StringUtils.isEmpty(key)) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        memcachedClient.delete(key);  
    }  

}  
4.使用方式

获取到memcachedUtils类,调用其方法即可

第三种
1.附上与maven集成的依赖
代码语言:javascript
复制
 <dependency>  
    <groupId>com.googlecode.xmemcached</groupId>  
    <artifactId>xmemcached</artifactId>  
     <version>2.0.0</version>  
</dependency> 
2.配置文件x-memcached.xml
代码语言:javascript
复制
    <!-- 注入自己写的类 -->  
        <bean id="cacheService" class="com.sss.util.XMemcachedClient">  
        </bean>  
        <bean name="memcachedClient"  
            class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean"  
            destroy-method="shutdown">  
            <property name="servers">  
                <value>127.0.0.1:11211</value>  
            </property>  
        </bean>  

或者

代码语言:javascript
复制
<?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:util="http://www.springframework.org/schema/util"  
    xmlns:jee="http://www.springframework.org/schema/jee"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd  
           http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">  

     <bean name="memcachedServers" class="java.net.InetSocketAddress"  
        factory-method="getAddresses">  
        <constructor-arg value="127.0.0.1:11211" />  
    </bean>  

    <bean name="memcachedClientBuilder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder">  
        <constructor-arg index="0" ref="memcachedServers" />   
        <property name="connectionPoolSize" value="1"></property>  
        <property name="commandFactory">  
            <bean class="net.rubyeye.xmemcached.command.TextCommandFactory"></bean>  
        </property>  
        <property name="sessionLocator">  
            <bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator"></bean>  
        </property>  
        <property name="transcoder">  
            <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" />  
        </property>  
    </bean>  

    <bean name="memcachedClient" factory-bean="memcachedClientBuilder"  
        factory-method="build" destroy-method="shutdown" />   

    <!-- 注入自己写的类 -->  
    <bean id="cacheService" class="com.sss.util.XMemcachedClient">  
    </bean>        
</beans> 
3.封装的memcached使用类
代码语言:javascript
复制
import net.rubyeye.xmemcached.MemcachedClient;  

import org.apache.commons.lang3.StringUtils;  
import org.slf4j.LoggerFactory;  
import org.springframework.beans.factory.annotation.Autowired;  

public class XMemcachedClient {  

    protected org.slf4j.Logger logger = LoggerFactory  
            .getLogger(this.getClass());  

    @Autowired  
    private MemcachedClient memcachedClient;  
    /*** 
     * 添加缓存 
     *  
     * @param key 
     * @param value 
     * @param expiry 
     *            超时时间(单位:分钟) 
     * @throws Exception 
     */  
    public void addCache(String key, Object value, int expiry) throws Exception {  

        if (StringUtils.isEmpty(key) || value == null) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
         boolean isCache = memcachedClient.add(key, expiry*60, value);  

        if (!isCache) {  
            throw new IllegalStateException("缓存存储失败!");  
        }  
    }  

    public Object findCache(String key) throws Exception {  
        if (StringUtils.isEmpty(key)) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        return memcachedClient.get(key);  
    }  

    public void deleteCache(String key) throws Exception {  
        if (StringUtils.isEmpty(key)) {  
            throw new IllegalArgumentException("参数错误!");  
        }  
        memcachedClient.delete(key);  
    }  
}  
4.使用方式

获取到XMemcached类调用其方法即可。

jar包资源

http://download.csdn.net/detail/u011269546/8221111 http://download.csdn.net/detail/u011269546/8221139 http://download.csdn.net/detail/u011269546/8220099

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-01-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 国产程序员 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 三者差异与性能比对
  • 三者具体使用
    • 第一种
      • 1.配置文件memcached.xml
      • 2.封装的memcached的使用类
      • 3.使用方式
    • 第二种
      • 1.附上与maven集成的依赖
      • 2.配置文件 spy-memcached.xml
      • 3.封装的memcached使用类
      • 4.使用方式
    • 第三种
      • 1.附上与maven集成的依赖
      • 2.配置文件x-memcached.xml
      • 3.封装的memcached使用类
      • 4.使用方式
  • jar包资源
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档