许鹏程
2023-06-29 e7ccc6e4243d7d7bfb4a950367b2cdc26428915f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package com.product.datasource.utils;
 
import com.product.core.spring.context.SpringMVCContextHolder;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @Author cheng
 * @Date 2022/12/6 20:42
 * @Desc
 */
public class RedisSentinelUtil {
 
    private List<Pool> jedisPools = new ArrayList<>();
 
    private String masterName;
 
    private GenericObjectPoolConfig poolConfig;
 
    private Set<HostAndPort> sentinelSet;
 
    private CreateJedisPool createJedisPool = new CreateJedisPool() {
    };
 
    private JedisSentinelPool jedisSentinelPool;
 
    private final String PONG = "PONG";
 
 
    public RedisSentinelUtil(Set<String> sentinels, JedisSentinelPool jedisSentinelPool, GenericObjectPoolConfig poolConfig, String masterName) {
        this(sentinels, jedisSentinelPool, poolConfig, masterName, null);
    }
 
    public RedisSentinelUtil(Set<String> sentinels, JedisSentinelPool jedisSentinelPool, GenericObjectPoolConfig poolConfig, String masterName, CreateJedisPool createJedisPool) {
        Jedis jedis = jedisSentinelPool.getResource();
        if (!PONG.equals(jedis.ping())) {
            throw new RuntimeException("redis 连接错误");
        }
        this.poolConfig = poolConfig;
        this.masterName = masterName;
        this.createJedisPool = createJedisPool != null ? createJedisPool : this.createJedisPool;
        this.jedisSentinelPool = jedisSentinelPool;
        this.sentinelSet = sentinels.stream().map(item -> HostAndPort.parseString(item)).collect(Collectors.toSet());
        changeSlave();
    }
 
    void changeSlave(Pool pool) {
        closePool(pool);
        this.changeSlave();
    }
 
    private void closePool(Pool pool) {
        if (pool == null) {
            return;
        }
        try {
            synchronized (jedisPools) {
                this.jedisPools.remove(pool);
            }
            pool.getJedisPool().close();
        } catch (Exception e) {
        }
    }
 
    private void changeSlave() {
        try {
            List<HostAndPort> redisClient = new ArrayList<>();
            try {
                for (HostAndPort hostAndPort : this.sentinelSet) {
                    Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort());
                    List<Map<String, String>> maps = jedis.sentinelSlaves(this.masterName);
                    for (Map<String, String> map : maps) {
                        String ip = map.get("ip");
                        String port = map.get("port");
                        HostAndPort slaveHostAndPort = new HostAndPort(ip, Integer.valueOf(port));
                        if (redisClient.contains(slaveHostAndPort)) {
                            continue;
                        }
                        redisClient.add(slaveHostAndPort);
                    }
                    jedis.close();
                }
            } catch (Exception e) {
 
            }
            if (jedisPools != null && !jedisPools.isEmpty()) {
                for (int i = 0; i < jedisPools.size(); i++) {
                    Pool pool = jedisPools.get(i);
                    if (!redisClient.contains(pool)) {
                        JedisPool jedisPool = pool.getJedisPool();
                        if (!jedisPool.isClosed()) {
                            try {
                                jedisPool.close();
                            } catch (Exception e) {
                            }
                        }
                        synchronized (jedisPools) {
                            jedisPools.remove(i);
                        }
                        i--;
                    }
                }
            }
            synchronized (jedisPools) {
                for (HostAndPort hostAndPort : redisClient) {
                    jedisPools.add(new Pool(hostAndPort, createJedisPool.create(hostAndPort, this.poolConfig)));
                }
            }
 
        } catch (Exception e) {
            if (jedisPools != null && !jedisPools.isEmpty()) {
                for (int i = 0; i < jedisPools.size(); i++) {
                    closePool(jedisPools.get(i));
                }
            }
            e.printStackTrace();
            SpringMVCContextHolder.getSystemLogger().error("创建Slave Redis连接池出错");
            SpringMVCContextHolder.getSystemLogger().error(e);
        }
    }
 
    /**
     * 获取只读的Redis连接
     * 若获取角色为 slave的失败则会获取master
     *
     * @return
     */
    public Jedis getResource() {
        Pool pool = null;
        try {
            synchronized (jedisPools) {
                if (jedisPools != null && !jedisPools.isEmpty()) {
                    pool = jedisPools.get(0);
                    //将已取出的对象移到集合尾部 实现简单的负载均衡
                    Collections.swap(jedisPools, 0, jedisPools.size() - 1);
                } else {
                    changeSlave();
                    if (jedisPools != null && !jedisPools.isEmpty()) {
                        return getResource();
                    }
                }
            }
            if (pool != null) {
                Jedis resource = pool.getJedisPool().getResource();
 
                System.out.println(String.format("获取到只读连接host:%s,port:%s", resource.getClient().getHost(),resource.getClient().getPort()));
                return resource;
            }
        } catch (Exception e) {
            e.printStackTrace();
            SpringMVCContextHolder.getSystemLogger().error("获取Slave Redis连接出错");
            SpringMVCContextHolder.getSystemLogger().error(e);
            changeSlave(pool);
        }
 
        return this.jedisSentinelPool.getResource();
    }
 
    interface CreateJedisPool {
        default JedisPool create(HostAndPort hostAndPort, GenericObjectPoolConfig poolConfig) {
            return new JedisPool(poolConfig, hostAndPort.getHost(), hostAndPort.getPort());
        }
    }
 
    class Pool {
        private HostAndPort hostAndPort;
 
        private JedisPool jedisPool;
 
        public Pool(HostAndPort hostAndPort, JedisPool jedisPool) {
            this.hostAndPort = hostAndPort;
            this.jedisPool = jedisPool;
        }
 
        public HostAndPort getHostAndPort() {
            return hostAndPort;
        }
 
        public JedisPool getJedisPool() {
            return jedisPool;
        }
 
 
        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (obj instanceof HostAndPort) {
                return this.hostAndPort.equals(obj);
            }
            return super.equals(obj);
        }
    }
}