Quantcast
Channel: IT社区推荐资讯 - ITIndex.net
Viewing all articles
Browse latest Browse all 11804

Xmemcached使用之与Spring整合

$
0
0

 

 

<dependency>
    <groupId>com.googlecode.xmemcached</groupId>
    <artifactId>xmemcached</artifactId>
    <version>1.4.3</version>
    <type>pom</type>
</dependency>

 

项目启动配置文件:

 

 

<?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="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:memcachedconf.properties</value></list></property></bean><import resource="classpath:spring/clerk-memcached.xml"/></beans>

 

 

 

clerk-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--xmemcached 配置--><bean name="xmemcachedClient" class="net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean"
          destroy-method="shutdown"><property name="servers" value="${memcached.servers}"/><property name="weights"><list><value>1</value><value>2</value><value>3</value></list></property><property name="connectionPoolSize" value="${memcached.connectionPoolSize}"/><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><property name="failureMode" value="true"/></bean><!--简单封装的memcached客户端--><bean name="memcachedClient" class="com.si.util.Memcached"><property name="isOpen" value="${memcached.isOpen}"/><property name="expires" value="${memcached.expires}"/><property name="memcachedClient" ref="xmemcachedClient"/></bean></beans>

 

 

其中各参数的意义:

参数

含义

servers

服务器列表,格式:ip:port

weights

主机映射:host1对应1号、host2对应2号..

sessionLocator

Session 分配器,有自带的,影响分布式

transcoder

通信编码方式

bufferAllocator

缓冲区分配器

 

 

 

memcachedconf.properties中的代码如下

 

 

#memcached开关
memcached.isOpen=true
#过期时间15分钟,单位(秒)
memcached.expires=3600
#memcached服务器列表
memcached.servers=host1:port1 host2:port2
#memcached 连接池大小
memcached.connectionPoolSize=30

 

 

com.si.clerk.util.Memcached的java类代码

 

 

package com.si.util;

import net.rubyeye.xmemcached.MemcachedClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

public class Memcached {
    private static Log log = LogFactory.getLog(Memcached.class);
    private boolean isOpen; // Memcached 开关
    private int expires;    // 默认过期时间
    private MemcachedClient mc;

    /*
    add 仅当存储空间中不存在键相同的数据时才保存
     */
    public <T> void addWithNoReply(String key, T value) {
        this.addWithNoReply(key, expires, value);
    }

    /**
     * 设置键值对
     * @param key     key
     * @param expires 单位:秒,0 表示永不过期
     * @param value   必须是一个可序列化的对象, 可以是容器类型如:List,但容器里面保存的对象必须是可序列化的
     */
    public <T> void addWithNoReply(String key, int expires, T value) {
        if (StringUtil.isEmpty(key)) return;
        try {
            if (isOpen && mc != null) {
                mc.addWithNoReply(key, expires, value);
            }
        } catch(Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /*
    set 无论何时都保存
     */
    public <T> void set(String key, T value) {
        this.set(key, expires, value);
    }

    /**
     * 设置键值对
     * @param key     key
     * @param expires 单位:秒,0 表示永不过期
     * @param value   必须是一个可序列化的对象, 可以是容器类型如:List,但容器里面保存的对象必须是可序列化的
     */
    public <T> void set(String key, int expires, T value) {
        if (StringUtil.isEmpty(key)) return;
        try {
            if (isOpen && mc != null) {
                mc.set(key, expires, value);
            }
        } catch(Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 根据key获得值
     * @param key key
     * @return value
     */
    public <T> T get(String key) {
        try {
            if (!StringUtil.isEmpty(key) && isOpen && mc != null) {
                return (T)mc.get(key);
            }
        } catch(Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 给每个原始key加上前缀后,再查。
     * @param keys                 原始key
     * @param memcachedKeyPrefix   前缀
     * @return
     */
    public <T> Map<String, T> getMulti(Collection keys, String memcachedKeyPrefix) {
        if (CommonTools.isEmpty(keys)) return null;
        if ("".equals(memcachedKeyPrefix)) {
            return this.get(keys);
        }
        List<String> strList = new ArrayList<String>();
        for (Object key : keys) {
            strList.add(memcachedKeyPrefix + String.valueOf(key));
        }
        return this.get(strList);
    }

    /**
     * 重载方法
     * @param keys
     * @param <T>
     * @return
     */
    public <T> Map<String, T> getMulti(Collection keys) {
        return getMulti(keys, "");
    }

    /**
     * 批量获取
     * @param keys keys
     * @return valueMap
     */
    private <T> Map<String, T> get(Collection<String> keys) {
        Map<String, T> map = null;
        try {
            if (keys != null && isOpen && mc != null) {
                map = mc.get(keys);
            }
        } catch(Exception e) {
            log.error(e.getMessage(), e);
        }
        return map;
    }

    public void setIsOpen(boolean open) {
        isOpen = open;
    }

    public void setExpires(int expires) {
        this.expires = expires;
    }

    public void setMemcachedClient(MemcachedClient mc) {
        this.mc = mc;
    }


}

 

 

 

 



已有 0人发表留言,猛击->> 这里<<-参与讨论


ITeye推荐




Viewing all articles
Browse latest Browse all 11804

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>