Java操作memcached(一)

Memcached事实上,两次Hash算法
   第一次hash算法被用于定位Memcached示例
   第二次hash算法是底部HashMap中间hash算法


Hash算法
     1.依据余数来进行计算(事实上java中的HashMap的hash算法也是用的这样的方式)
     2.一致性hash算法
         C的client  --->libMemcached已经实现了该功能,C的开发者直接使用它。
新浪----->Memcachedb  实现了持久化功能


java的client
 a官方的 memcached client for java
    比較稳定
    用了jdk比較早的版本号。性能稍差,而且使用的BIO
 b.spyMemcached
    NIO,线程池框架
    一致性hash
    稳定性差,报timeout异常
 c.xMemcached 
     java nio
     java 线程池
     性能比spyMemcached要好
     而且比較稳定,且和spring等框架可以非常好的结合使用
     一致性hash
 d.淘宝包装的javaclient
   java nio
   线程池框架
   cluster机制

   结合本地缓存


接下来我们使用第一种  


这是须要的jar

package com.chengxi.memc.test;

import org.junit.Test;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class MemcachedTest01 {
	@Test
	public void testOne() throws Exception {
		
		MemCachedClient client = new MemCachedClient();
		//memserver地址
		String[] addr = {"192.168.0.140:11211"};
		//相应的权重
		Integer[] weight = {3};
		SockIOPool pool = SockIOPool.getInstance();
		
		pool.setServers(addr);
		pool.setWeights(weight);
		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(200);
		pool.setMaxIdle(1000*30*30);
		pool.setMaintSleep(30);
		
		//socket param timeout 
		pool.setNagle(false);
		pool.setSocketTO(30);
		pool.setSocketConnectTO(0);
		
		//start 
		pool.initialize();
		
		//client.set("name", "wzh");
		//System.out.println(client.get("name"));
		Student student = new Student();
		student.setId(1);
		student.setName("呵呵");
		
		client.set("student1",student);
		
		System.out.println(client.get("student1"));
	}
	
	@Test
	public void two(){
		MemCachedClient client = new MemCachedClient();
		//memserver地址
		String[] addr = {"192.168.0.140:11211","192.168.0.140:11212"};
		//相应的权重
		Integer[] weight = {5,5};
		SockIOPool pool = SockIOPool.getInstance();
		
		pool.setServers(addr);
		pool.setWeights(weight);
		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(200);
		pool.setMaxIdle(1000*30*30);
		pool.setMaintSleep(30);
		
		//socket param timeout 
		pool.setNagle(false);
		pool.setSocketTO(30);
		pool.setSocketConnectTO(0);
		
		//start 
		pool.initialize();
		
		for(int i  = 0;i<10;i++){
			client.set("test"+i,"test"+i);
		}
		
	}
}

官方的jar包实现了 哈希一致性

也就是说  上面的 two的方法  分别将test0-9 存进了两台memserver中

假设当中一台宕机了   获取数据的时候不会影响另外一台

假设没有实现一致哈希的话 就会影响其它server 导致全部的数据无法获取

package com.chengxi.memc.test;

import java.io.Serializable;

public class Student implements Serializable {
	private Integer id;
	private String name;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "[id:"+this.id+",name"+this.name+"]";
	}
}

这是实体类 为了实现系列化


版权声明:本文博主原创文章,博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/lcchuguo/p/4808004.html