Spring之十二 整合memcache

1.安装缓存系统

d:\memcached-win32-1.4.4-14\memcached.exe -d install
d:\memcached-win32-1.4.4-14\memcached.exe -d start

2.加入jar包

xmemcached-2.0.0.jar

3.添加配置文件xmemcached.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:p="http://www.springframework.org/schema/p"
    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">
    <bean id="memcachedClientBuilder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder">
        <constructor-arg>
            <list>
                <bean class="java.net.InetSocketAddress">
                    <constructor-arg value="localhost"/>
                    <constructor-arg value="11211"/>
                </bean>
            </list>
        </constructor-arg>
        <property name="connectionPoolSize" value="5"/>
        <property name="failureMode" value="true"/>
        <property name="commandFactory">
            <bean class="net.rubyeye.xmemcached.command.TextCommandFactory"/>
        </property>
        <property name="sessionLocator">
            <bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" />
        </property>
        <property name="transcoder">
            <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" />
        </property>
<!--        <property name="socketOption">
            <map>
                <entry key="SO_RCVBUF" value="32768"/>
                <entry key="SO_SNDBUF" value="16384"/>
                <entry key="TCP_NODELAY" value="false"/>
            </map>
        </property>
        <property name="configuration">
            <bean class="com.google.code.yanf4j.config.Configuration" p:statisticsServer="false"/>
        </property>-->
    </bean>
    <bean id="memcachedClient" 
          factory-bean="memcachedClientBuilder"
          factory-method="build"
          destroy-method="shutdown" />
<!--      p:enableHeartBeat="false"
          p:mergeFactor="150"
          p:optimizeGet="true"
          p:optimizeMergeBuffer="true"-->
</beans>

4.在applicationContext.xml中导入该bean

<import resource="xmemcached.xml"/>

5.封装缓存工具

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ithings.cache;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import javax.annotation.Resource;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientCallable;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 *缓存工具类
 */
@Component
public class MemcacheManager {

    private Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private MemcachedClient memcachedClient;

    /**
     * 添加或修改一个对象到缓存
     * @param namespace
     * @param key 缓存key值
     * @param value 缓存对象(必须是可序列化(Serializer)的对象)
     * @return 
     */
    public boolean put(final String namespace, final String key, final Object value) {
        boolean flag = false;
        try {
            this.memcachedClient.withNamespace(namespace,
                new MemcachedClientCallable<Void>() {

                    @Override
                    public Void call(MemcachedClient client)
                            throws MemcachedException, InterruptedException, TimeoutException {
                        client.set(key, 0, value);
                        return null;
                    }
                });
            flag = true;
        } catch (Exception e) {
            logger.error(null, e);
        }
        return flag;
    }

    /**
     * 添加一个缓存
     *
     * @param namespace
     * @param key
     * @param value
     * @return
     */
    public boolean add(final String namespace, final String key, final Object value) {
        boolean flag = false;
        try {
            this.memcachedClient.withNamespace(namespace,
                    new MemcachedClientCallable<Void>() {

                        @Override
                        public Void call(MemcachedClient client)
                                throws MemcachedException, InterruptedException,
                                TimeoutException {
                            client.add(key, 0, value);
                            return null;
                        }
                    });
            flag = true;
        } catch (Exception e) {
            logger.error(null, e);
        }
        return flag;
    }

    /**
     * 更新存在的缓存
     *
     * @param namespace
     * @param key
     * @param value
     * @return
     */
    public boolean update(final String namespace, final String key, final Object value) {
        boolean flag = false;
        try {
            this.memcachedClient.withNamespace(namespace,
                    new MemcachedClientCallable<Void>() {

                        @Override
                        public Void call(MemcachedClient client)
                                throws MemcachedException, InterruptedException,
                                TimeoutException {
                            client.replace(key, 0, value);
                            return null;
                        }
                    });
            flag = true;
        } catch (Exception e) {
            logger.error(null, e);
        }
        return flag;
    }

    /**
     * 获取一个缓存对象
     *
     * @param <T>
     * @param namespace
     * @param key 缓存存储key
     * @return 缓存对象
     */
    public <T> T get(final String namespace, final String key) {
        T t = null;
        try {
            t = this.memcachedClient.withNamespace(namespace,
                    new MemcachedClientCallable<T>() {

                        @Override
                        public T call(MemcachedClient client)
                                throws MemcachedException, InterruptedException,
                                TimeoutException {
                            return client.get(key);
                        }
                    });
        } catch (Exception e) {
            logger.error(null, e);
        }
        return t;
    }

    /**
     * 获取一个缓存对象
     *
     * @param <T>
     * @param namespace
     * @param key 缓存存储key
     * @param timeout
     * @return 缓存对象
     */
    public <T> T get(final String namespace, final String key, final long timeout) {
        T t = null;
        try {
            t = this.memcachedClient.withNamespace(namespace,
                    new MemcachedClientCallable<T>() {

                        @Override
                        public T call(MemcachedClient client)
                                throws MemcachedException, InterruptedException,
                                TimeoutException {
                            return client.get(key, timeout);
                        }
                    });
        } catch (Exception e) {
            logger.error(null, e);
        }
        return t;
    }

    /**
     * 获取多个缓存对象
     *
     * @param <T>
     * @param namespace
     * @param keys 缓存存储key
     * @return 缓存对象
     */
    public <T> Map<String, T> get(final String namespace, final Collection<String> keys) {
        Map<String, T> valueMap = null;
        try {
            valueMap = this.memcachedClient.withNamespace(namespace,
                    new MemcachedClientCallable<Map<String, T>>() {

                        @Override
                        public Map<String, T> call(MemcachedClient client)
                                throws MemcachedException, InterruptedException,
                                TimeoutException {
                            return client.get(keys);
                        }
                    });
        } catch (Exception e) {
            logger.error(null, e);
        }
        return valueMap;
    }

    /**
     * 获取多个缓存对象
     *
     * @param <T>
     * @param namespace
     * @param keys 缓存存储key
     * @param timeout
     * @return 缓存对象
     */
    public <T> Map<String, T> get(final String namespace, final Collection<String> keys, final long timeout) {
        Map<String, T> valueMap = null;
        try {
            valueMap = this.memcachedClient.withNamespace(namespace,
                    new MemcachedClientCallable<Map<String, T>>() {

                        @Override
                        public Map<String, T> call(MemcachedClient client)
                                throws MemcachedException, InterruptedException,
                                TimeoutException {
                            return client.get(keys, timeout);
                        }
                    });
        } catch (Exception e) {
            logger.error(null, e);
        }
        return valueMap;
    }

    /**
     * 移除一个缓存对
     *
     * @param namespace
     * @param key 缓存对象key
     * @return 移除状态
     */
    public boolean remove(final String namespace, final String key) {
        boolean flag = false;
        try {
            this.memcachedClient.withNamespace(namespace,
                    new MemcachedClientCallable<Void>() {

                        @Override
                        public Void call(MemcachedClient client)
                                throws MemcachedException, InterruptedException,
                                TimeoutException {
//                            client.deleteWithNoReply(key);
                            client.delete(key);
                            return null;
                        }
                    });
            flag = true;
            flag = true;
        } catch (Exception e) {
            logger.error(null, e);
        }
        return flag;
    }

    /**
     * 清除命名空间下的缓存数据
     *
     * @param namespace
     * @return 清除状态
     */
    public boolean clean(final String namespace) {
        boolean flag = false;
        try {
            this.memcachedClient.invalidateNamespace(namespace);
            flag = true;
        } catch (Exception e) {
            logger.error(null, e);
        }
        return flag;
    }
}


6.使用

    @Override
    public void cache(){
        memcacheManager.put("hello", "name", "mlu");
        System.out.println(memcacheManager.get("hello", "name"));
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值