Java使用memcached

jopen 11年前發布 | 117K 次閱讀 memcached 緩存服務器

1.加載commons-pool-1.5.6.jar、java_memcached-release_2.6.6.jar、slf4j-api-1.6.1.jar、slf4j-simple-1.6.1.jar

2.創建memcached工具類:

public class MemcachedUtil {

    /**
     * memcached客戶端單例
     */
    private static MemCachedClient cachedClient = new MemCachedClient();

    /**
     * 初始化連接池
     */
    static {
        //獲取連接池的實例
        SockIOPool pool = SockIOPool.getInstance();

        //服務器列表及其權重
        String[] servers = {"127.0.0.1:11211"};
        Integer[] weights = {3};

        //設置服務器信息
        pool.setServers(servers);
        pool.setWeights(weights);

        //設置初始連接數、最小連接數、最大連接數、最大處理時間
        pool.setInitConn(10);
        pool.setMinConn(10);
        pool.setMaxConn(1000);
        pool.setMaxIdle(1000*60*60);

        //設置連接池守護線程的睡眠時間
        pool.setMaintSleep(60);

        //設置TCP參數,連接超時
        pool.setNagle(false);
        pool.setSocketTO(60);
        pool.setSocketConnectTO(0);

        //初始化并啟動連接池
        pool.initialize();

        //壓縮設置,超過指定大小的都壓縮
//      cachedClient.setCompressEnable(true);
//      cachedClient.setCompressThreshold(1024*1024);
    }

    private MemcachedUtil(){
    }

    public static boolean add(String key, Object value) {
        return cachedClient.add(key, value);
    }

    public static boolean add(String key, Object value, Integer expire) {
        return cachedClient.add(key, value, expire);
    }

    public static boolean put(String key, Object value) {
        return cachedClient.set(key, value);
    }

    public static boolean put(String key, Object value, Integer expire) {
        return cachedClient.set(key, value, expire);
    }

    public static boolean replace(String key, Object value) {
        return cachedClient.replace(key, value);
    }

    public static boolean replace(String key, Object value, Integer expire) {
        return cachedClient.replace(key, value, expire);
    }

    public static Object get(String key) {
        return cachedClient.get(key);
    }

}
3. 創建需要緩存的對象:

public class UserBean implements Serializable {

    private static final long serialVersionUID = 9174194101246733501L;

    private String username;

    private String password;

    public UserBean(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((password == null) ? 0 : password.hashCode());
        result = prime * result
                + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        UserBean other = (UserBean) obj;
        if (password == null) {
            if (other.password != null)
                return false;
        } else if (!password.equals(other.password))
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "username:" + username + ",password:" + password;
    }
}
4.創建測試用例:

public class MemcachedUtilTest {

    @Test
    public void testMemcached() {
        MemcachedUtil.put("hello", "world", 60);
        String hello = (String) MemcachedUtil.get("hello");
        Assert.assertEquals("world", hello);

        for(int i = 0; i < 10000000; ++i) {
            UserBean userBean = new UserBean("Jason" + i, "123456-" + i);
            MemcachedUtil.put("user" + i, userBean, 60);
            Object obj = MemcachedUtil.get("user" + i);
            Assert.assertEquals(userBean, obj);
        }
    }
}

5.通過spring注入memcached:

<?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</value>
        </property>
        <property name="minConn">
            <value>10</value>
        </property>
        <property name="maxConn">
            <value>50</value>
        </property>
        <property name="nagle">
            <value>false</value>
        </property>
        <property name="socketTO">
            <value>3000</value>
        </property>
    </bean>
    <bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient">
        <constructor-arg>
            <value>neeaMemcachedPool</value>
        </constructor-arg>
    </bean>
</beans>

6.創建測試用例:

public class MemcachedSpringTest {

    private MemCachedClient cachedClient;

    @Before
    public void init() {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/loujinhe/config/beans.xml");
        cachedClient = (MemCachedClient)context.getBean("memcachedClient");
    }

    @Test
    public void testMemcachedSpring() {
        UserBean user = new UserBean("lou", "jason");
        cachedClient.set("user", user);
        UserBean cachedBean = (UserBean)user;
        Assert.assertEquals(user, cachedBean);
    }
}
來自:http://blog.csdn.net/loujinhe/article/details/8491673

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!