redis分片技术-01

需求:

  如果将全部数据都保存到一台redis中,那么如果该服务器损坏,则影响全部的服务;

  使用单台redis内存设定一般不要超过1G,但是有些业务数据量很大,如果不修改内存,则数据无法存储;

方案:

  采用redis分片技术;

  优点:

    1.使用redis分片可以实现内存数据的动态扩容;

    2.使用分片,每台redis节点中尽可能保存1/n的数据量,防止数据的丢失;

    3.对于用户而言,整个redis的分片就是一个服务;n台服务器作为一个整体的服务器共同为用户服务;

1.  分片搭建:

    1.1复制配置文件:新建shards文件夹,将redis.conf文件复制到shards文件中,并且复制3分,改名字,改端口号;

[root@localhost redis]# ls
00-RELEASENOTES  deps      MANIFESTO   runtest-cluster   src
BUGS             dump.rdb  README.md   runtest-sentinel  tests
CONTRIBUTING     INSTALL   redis.conf  sentinel.conf     utils
COPYING          Makefile  runtest     shards
[root@localhost redis]# cp redis.conf shards/redis-6379.conf
[root@localhost redis]# cp redis.conf shards/redis-6380.conf
[root@localhost redis]# cp redis.conf shards/redis-6381.conf
[root@localhost redis]# ll

结果:

 [root@localhost redis]# cd shards/
 [root@localhost shards]# ll
 total 144
 -rw-r--r--. 1 root root 46696 Nov 2 22:51 redis-6379.conf
 -rw-r--r--. 1 root root 46696 Nov 2 22:51 redis-6380.conf
 -rw-r--r--. 1 root root 46696 Nov 2 22:51 redis-6381.conf

    1.2确认启动是否成功:

[root@localhost shards]# redis-server redis-6379.conf 
[root@localhost shards]# redis-server redis-6380.conf 
[root@localhost shards]# redis-server redis-6381.conf 
[root@localhost shards]# ps -ef |grep redis
root      2845     1  0 22:58 ?        00:00:00 redis-server *:6379         
root      2849     1  0 22:58 ?        00:00:00 redis-server *:6380         
root      2853     1  0 22:59 ?        00:00:00 redis-server *:6381         
root      2857  2585  0 22:59 pts/0    00:00:00 grep redis

    1.3测试:

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class TestShardRedis {

    @Test
    public void testShard(){
        /**
         * 创建分片的对象
         * 1.poolConfig    标示池的大小
         * 2.shards        redis分片的节点信息
         */
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(1000);
        poolConfig.setTestOnBorrow(true);//获取连接时,先检测,如果不行就换一个

        List<JedisShardInfo> shards = new ArrayList<>();
        shards.add(new JedisShardInfo("192.168.25.132", 6379));
        shards.add(new JedisShardInfo("192.168.25.132", 6380));
        shards.add(new JedisShardInfo("192.168.25.132", 6381));

        ShardedJedisPool pool = new ShardedJedisPool(poolConfig, shards);

        //获取redis的连接
        ShardedJedis jedis = pool.getResource();

        jedis.set("shards", "保存分片的数据");
        System.out.println(jedis.get("shards"));

        //还回连接到pool
        pool.returnResource(jedis);
    }
}

输出:保存分片的数据
原文地址:https://www.cnblogs.com/yikuan-919/p/9900665.html