Memcached
Memcache是一套开源,高性能的分布式的内存对象缓存系统。Memcache将所有数据存储在内存中,并在内存里维护一个统一的巨大的Hash表,它能存储任意类型的数据,包括图像、视频、文件以及数据库检索的结果等。将数据调用到内存中,然后从内存中读取,从而大大提高读取速度
安装Memcached
(1)下载和安装libevent
git clone https://github.com/linxuping/libevent.git
./configure -prefix=/usr/local/libevent
make
make install
(2)下载和安装memcached
tar -xvzf memcached-1.5.16.tar.gz
./configure -prefix=/usr/local/memcached -with-libevent=/usr/local/libevent
make
make install
(3)启动memcached
./memcached -u root -d -m 128 -p 11211
./memcached -u root -d -m 128 -p 11212
./memcached -u root -d -m 128 -p 11213
(4)查看memcached进程
ps -ef | grep memcached
(5)操作memcached
telnet 192.168.138.130 11211
set key 0 0 4
abcd
get key
Java操作Memcached
package com.memcache.util;
import net.spy.memcached.MemcachedClient;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* @author Administrator
* @version 1.0
*/
public class Memcache {
private MemcachedClient client;
/**
* 连接memcached
* @throws IOException
*/
@Before
public void connectClient() throws IOException {
client = new MemcachedClient(new InetSocketAddress("192.168.138.130",11211));
}
/**
* 设置key
* @throws ExecutionException
* @throws InterruptedException
*/
@Test
public void setKey() throws ExecutionException, InterruptedException {
Future<Boolean> future = client.set("key1", 0, "Hello World");
if (future.get().booleanValue()){
client.shutdown();
}
}
@Test
public void getKey(){
Object o = client.get("key1");
System.out.println("取到的值: "+o);
client.shutdown();
}
/**
* 设置对象的值
* @throws ExecutionException
* @throws InterruptedException
*/
@Test
public void setObject() throws ExecutionException, InterruptedException {
Future<Boolean> future = client.set("key2", 0, new Student());
if (future.get().booleanValue()){
client.shutdown();
}
}
/**
* 客户端路由算法
* @throws IOException
* @throws InterruptedException
*/
@Test
public void connectList() throws IOException, InterruptedException {
ArrayList<InetSocketAddress> list = new ArrayList<>();
list.add(new InetSocketAddress("192.168.138.130",11211));
list.add(new InetSocketAddress("192.168.138.130",11212));
list.add(new InetSocketAddress("192.168.138.130",11213));
//连接Memcached
client = new MemcachedClient(list);
for (int i = 0; i < 10; i++){
client.set("key"+i,0,"value"+i);
Thread.sleep(1000);
}
client.shutdown();
}
}
class Student implements Serializable {}
Memcached的路由算法
(1)求余数Hash算法
用key做hash运算得到一个整数,根据余数路由
优点:数据分布均衡在多台服务器中,适合大多数据需求
缺点:如果需要扩容或者有宕机的情况,会造成数据的丢失