1. 集群方案 - 客户端支持


image.png

  • Java 客户端根据 key,通过 hash 取模或者其他一致性算法,最终选择一个 server 进行连接。

    启动三台服务器

    1. /usr/local/memcached/bin/memcached -m 64 -p 11211 -u root -v -d
    2. /usr/local/memcached/bin/memcached -m 64 -p 11212 -u root -v -d
    3. /usr/local/memcached/bin/memcached -m 64 -p 11213 -u root -v -d

自己写一个简单的服务器选择

/**
 * 客户端集群工具类
 */
public class ClusterClientFactory {

    /**
     * 根据 key 选择客户端
     */
    public static MemcachedClient getClient(String key) throws IOException {
        ArrayList<XMemcachedClient> servers = new ArrayList<>();
        servers.add(new XMemcachedClient("127.0.0.1", 11211));
        servers.add(new XMemcachedClient("127.0.0.1", 11212));
        servers.add(new XMemcachedClient("127.0.0.1", 11213));

        // 计算 key 的 hash 值
        int hashCode = Math.abs(key.hashCode());
        // 计算对应的位置(直接和服务器数量取模)
        int slot = hashCode % servers.size();

        return servers.get(slot);
    }

}
/**
 * 使用自己写的客户端集群方案
 */
@Service
@Profile("cluster")
public class UserServiceByCustom {

    public User findUser(String userId) throws Exception {
        // 每次根据情况进行选择
        MemcachedClient client = ClusterClientFactory.getClient(userId);
        User user;

        // 1. 判断缓存中是否存在
        user = client.get(userId);
        if (user != null) {
            System.out.println("从缓存中读取到值:" + user);
            return user;
        }

        // TODO 2. 不存在则读取数据库或者其他地方的值
        user = new User(userId, "张三");
        System.out.println("从数据库中读取到值" + user);

        // 3. 同步存储 value 到 memcached,缓存超时为 1 小时,3600 秒
        client.set(userId, 3600, user);

        return user;
    }

}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@ActiveProfiles("cluster")
public class CustomClusterTests {

    @Autowired
    private UserServiceByCustom userServiceByCustom;

    @Test
    public void custerClientClusterTest() throws Exception {
        userServiceByCustom.findUser("zhangsan");
        userServiceByCustom.findUser("lisi");
        userServiceByCustom.findUser("wangwu");
        userServiceByCustom.findUser("zhaoliu");
        userServiceByCustom.findUser("qianqi");
        userServiceByCustom.findUser("wuba");
    }

}

使用第三方插件进行集群服务器选择

@Configuration
@Profile("cluster")
public class ClusterAppConfig {

    @Bean
    public MemcachedClient memcachedClient() throws IOException {
        String server = "127.0.0.1:11211 127.0.0.1:11212 127.0.0.1:11213";
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(
                AddrUtil.getAddresses(server));
        // 默认的客户端计算就是 key 的哈希值对连接数取模
        // KetamaMemcachedSessionLocator 一致性 hash 算法
        builder.setSessionLocator(new KetamaMemcachedSessionLocator());
        return builder.build();
    }

}
@Service
@Profile("cluster")
public class UserService {

    @Resource
    private MemcachedClient memcachedClient;

    public User findUser(String userId) throws Exception {
        User user;

        // 1. 判断缓存中是否存在
        user = memcachedClient.get(userId);
        if (user != null) {
            System.out.println("从缓存中读取到值:" + user);
            return user;
        }

        // TODO 2. 不存在则读取数据库或者其他地方的值
        user = new User(userId, "张三");
        System.out.println("从数据库中读取到值" + user);

        // 3. 同步存储 value 到 memcached,缓存超时为 1 小时,3600 秒
        memcachedClient.set(userId, 3600, user);

        return user;
    }

}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@ActiveProfiles("cluster")
public class ClientClusterTests {

    @Autowired
    private UserService userService;

    @Test
    public void xmemcachedClientClusterTest() throws Exception {
        userService.findUser("zhangsan");
        userService.findUser("lisi");
        userService.findUser("wangwu");
        userService.findUser("zhaoliu");
        userService.findUser("qianqi");
        userService.findUser("wuba");
    }

}

2. 集群方案 - Twemproxy


image.png

  • 推特开源的中间件,实现 memcached 代理。
  • 对于 JAVA 应用程序就像使用一个普通的 memcached 一样。

    安装使用

  • 查看相关资料中的文件《memcached单机到集群完整搭建过程》

  • 安装过程中可能会报以下错误

image.png

  • 处理办法:安装插件 libtool,命令 yum install libtool
    • 配置文件
      memcached:
      listen: 127.0.0.1:22121
      hash: fnv1a_64
      distribution: ketama
      timeout: 400
      backlog: 1024
      preconnect: true
      auto_eject_hosts: true
      server_retry_timeout: 30000
      server_failure_limit: 3
      servers:
      - 127.0.0.1:11211:1
      - 127.0.0.1:11212:1
      

问题

  • 所有的请求都经过了代理,会有瓶颈问题。
  • 假如代理之后,会增加性能损耗。