Java Redis缓存操作(哨兵模式)

释放双眼,带上耳机,听听看~!

一、添加jedis的maven依赖


1
2
3
4
5
6
1<dependency>
2    <groupId>redis.clients</groupId>
3    <artifactId>jedis</artifactId>
4    <version>2.9.0</version>
5</dependency>
6

二、在配置cache.properties文件中配置哨兵模式redis信息


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
1# 单节点配置
2#redis.host = 127.0.0.1
3#redis.port = 6379
4
5# 集群节点,集群模式下配置
6#redis.cluster.nodes = 12.2.3.14:7001,12.2.3.14:7002,12.2.3.14:7003,12.2.3.14:7004
7
8# 哨兵节点,哨兵模式下配置
9redis.sentinel.nodes = 12.2.3.14:7001,12.2.3.14:7002,12.2.3.14:7003,12.2.3.14:7004
10redis.sentinel.master = mymaster
11
12# ----redis common begin----
13# 密码
14#redis.password = 123456
15# 连接超时时间 单位 ms(毫秒)
16redis.timeout = 6000
17# 连接池中的最大空闲连接,默认值也是8
18redis.pool.max-idle = 8
19# 连接池中的最小空闲连接,默认值也是0
20redis.pool.min-idle = 0
21# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
22redis.pool.max-active = 8
23# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
24redis.pool.max-wait = -1
25# ----redis common end----
26

三、定义CacheConfig类来加载配置信息


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
1package com.ldy.common.cache;
2
3/**
4 * @author lidongyang
5 * @Description 缓存配置类
6 * @date 2019/6/21 8:38
7 */
8public class CacheConfig {
9
10    /**
11     * 单节点REDIS 地址
12     */
13    public static String REDIS_HOST = PropertiesUtils.getProperty("cache-config", "redis.host");
14
15    /**
16     * 单节点REDIS 端口
17     */
18    public static int REDIS_PORT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.port"));
19
20    /**
21     * 集群模式节点
22     */
23    public static String REDIS_CLUSTER_NODES = PropertiesUtils.getProperty("cache-config", "redis.cluster.nodes");
24
25    /**
26     * 哨兵模式节点
27     */
28    public static String REDIS_SENTINEL_NODES = PropertiesUtils.getProperty("cache-config", "redis.sentinel.nodes");
29
30    /**
31     * 哨兵模式 master
32     */
33    public static String REDIS_SENTINEL_MASTER = PropertiesUtils.getProperty("cache-config", "redis.sentinel.master");
34
35    /**
36     * REDIS 密码
37     */
38    public static String REDIS_PASSWORD = PropertiesUtils.getProperty("cache-config", "redis.password");
39
40    /**
41     * REDIS 连接超时时间 单位 ms(毫秒)
42     */
43    public static int REDIS_TIMEOUT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.timeout"));
44
45    /**
46     * 连接池中的最大空闲连接,默认值也是8
47     */
48    public static int REDIS_POOL_MAX_IDLE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-idle"));
49
50    /**
51     * 连接池中的最小空闲连接,默认值也是0
52     */
53    public static int REDIS_POOL_MIN_IDLE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.min-idle"));
54
55
56    /**
57     * # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
58     */
59    public static int REDIS_POOL_MAX_ACTIVE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-active"));
60
61    /**
62     * 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
63     */
64    public static int REDIS_POOL_MAX_WAIT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-wait"));
65
66}
67
68

1
2
3
1上面使用到的PropertiesUtils代码如下:
2
3

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
1package com.ldy.common.cache;
2import java.io.InputStream;
3import java.util.Properties;
4
5
6/**
7 *
8 * PropertiesUtils.java
9 * @desc properties 资源文件解析工具
10 * @author lidongyang
11 *
12 */
13public class PropertiesUtils {
14   private static Properties props;
15   
16      private static void readProperties(String fileName) {
17          InputStream fis = null;
18          try {
19              props = new Properties();
20              fis =PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName);
21              props.load(fis);
22          } catch (Exception e) {
23              e.printStackTrace();
24          } finally{
25              if(fis != null){
26                  try {
27                      fis.close();
28                  }catch(Exception e) {
29                      e.printStackTrace();
30                  }
31              }
32             
33          }
34      }
35     
36      /**
37       * 根据文件名和属性名获取属性值
38       * @author lidongyang
39       * @param fileName
40       * @param key
41       * @return
42       */
43      public synchronized static String getProperty(String fileName,String key){
44          readProperties(fileName+".properties");
45          return props.getProperty(key);
46      }
47     
48      public static void main(String[] args) {
49          String value = PropertiesUtils.getProperty("webconfig", "zip_path");
50          System.out.println("value:"+value);
51      }    
52}
53
54

四、编写RedisSentinelCache类用来操作redis


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
1package com.ldy.common.cache;
2
3
4import redis.clients.jedis.Jedis;
5import redis.clients.jedis.JedisPoolConfig;
6import redis.clients.jedis.JedisSentinelPool;
7
8import java.util.Date;
9import java.util.HashSet;
10import java.util.Set;
11
12/**
13 * @author lidongyang
14 * @Description 哨兵模式redis缓存接口
15 * @date 2019/6/20 16:45
16 */
17public class RedisSentinelCache {
18
19    private static JedisSentinelPool redisSentinelJedisPool = null;
20
21    public RedisSentinelCache() {
22        if (null == redisSentinelJedisPool) {
23            initPool();
24        }
25    }
26
27    private void initPool() {
28        JedisPoolConfig config = new JedisPoolConfig();
29        config.setMaxTotal(CacheConfig.REDIS_POOL_MAX_ACTIVE);
30        config.setMaxIdle(CacheConfig.REDIS_POOL_MAX_IDLE);
31        config.setMaxWaitMillis(CacheConfig.REDIS_POOL_MAX_WAIT);
32        // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的
33        config.setTestOnBorrow(true);
34        //在return给pool时,是否提前进行validate操作
35        config.setTestOnReturn(true);
36        //在空闲时检查有效性,默认false
37        config.setTestWhileIdle(true);
38        // 哨兵模式
39        String sentinelsStr = CacheConfig.REDIS_SENTINEL_NODES;
40        Set<String> sentinels = new HashSet<String>();
41        for (String sentinel : sentinelsStr.split(",")) {
42            sentinels.add(sentinel);
43        }
44        redisSentinelJedisPool = new JedisSentinelPool(CacheConfig.REDIS_SENTINEL_MASTER, sentinels, config, CacheConfig.REDIS_PASSWORD);
45    }
46
47    /**
48     * 同步获取Jedis实例
49     *
50     * @return
51     */
52    public synchronized  static Jedis getJedis() {
53        return redisSentinelJedisPool.getResource();
54    }
55
56
57    public String get(String key) {
58        Jedis jedis = getJedis();
59        if (jedis == null) {
60            System.out.println("Jedis实例获取失败!");
61            throw new RuntimeException();
62        }
63
64        try {
65            return jedis.get(key);
66        } catch (Exception e) {
67            System.out.println("获取值失败:" + e.getMessage());
68            throw new RuntimeException();
69        } finally {
70            if (null != jedis) {
71                jedis.close();
72            }
73        }
74    }
75
76
77    public Object getObject(String key) {
78        Jedis jedis = getJedis();
79        if (jedis == null) {
80            System.out.println("Jedis实例获取失败!");
81            throw new RuntimeException();
82        }
83
84        try {
85            byte[] data = jedis.get(key.getBytes());
86            return SerializeUtils.unserialize(data);
87        } catch (Exception e) {
88            System.out.println("获取值失败:" + e.getMessage());
89            throw new RuntimeException();
90        } finally {
91            if (null != jedis) {
92                jedis.close();
93            }
94        }
95    }
96
97    public void set(String key, String value) {
98        Jedis jedis = getJedis();
99        try {
100            jedis.set(key, value);
101        } catch (Exception e) {
102            System.out.println("设置值失败:" + e.getMessage());
103            throw new RuntimeException();
104        } finally {
105            if (null != jedis) {
106                jedis.close();
107            }
108        }
109    }
110
111    public void set(String key, String value, int second) {
112        Jedis jedis = getJedis();
113        try {
114            jedis.set(key, value);
115            jedis.expire(key, second);
116        } catch (Exception e) {
117            System.out.println("设置值失败:" + e.getMessage());
118            throw new RuntimeException();
119        } finally {
120            if (null != jedis) {
121                jedis.close();
122            }
123        }
124    }
125
126    public void setObject(String key, Object value) {
127        Jedis jedis = getJedis();
128        try {
129            jedis.set(key.getBytes(), SerializeUtils.serialize(value));
130        } catch (Exception e) {
131            System.out.println("设置值失败:" + e.getMessage());
132            throw new RuntimeException();
133        } finally {
134            if (null != jedis) {
135                jedis.close();
136            }
137        }
138    }
139
140    public void setObject(String key, Object value, int second) {
141        Jedis jedis = getJedis();
142        try {
143            jedis.set(key.getBytes(), SerializeUtils.serialize(value));
144            jedis.expire(key, second);
145        } catch (Exception e) {
146            System.out.println("设置值失败:" + e.getMessage());
147            throw new RuntimeException();
148        } finally {
149            if (null != jedis) {
150                jedis.close();
151            }
152        }
153    }
154
155    public void del(String key) {
156        Jedis jedis = getJedis();
157        try {
158            jedis.del(key);
159        } catch (Exception e) {
160            System.out.println("删除失败:" + e.getMessage());
161            throw new RuntimeException();
162        } finally {
163            if (null != jedis) {
164                jedis.close();
165            }
166        }
167    }
168
169
170    public static void main(String[] args) {
171        RedisSentinelCache cache = new RedisSentinelCache();
172
173        cache.set("ldy", "lisi");
174        System.out.println(cache.get("lisi"));
175        cache.del("lisi");
176
177        cache.setObject("date", new Date());
178        System.out.println(cache.getObject("date"));
179    }
180}
181
182

辅助工具类SerializeUtils代码如下


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
1package com.ldy.common.cache;
2
3import java.io.ByteArrayInputStream;
4import java.io.ByteArrayOutputStream;
5import java.io.ObjectInputStream;
6import java.io.ObjectOutputStream;
7
8/**
9 * @author lidongyang
10 * @Description 对象序列化工具类
11 * @date 2019/6/20 18:51
12 */
13public class SerializeUtils {
14
15    /**
16     * 序列化
17     * @param obj
18     * @return
19     */
20    public static byte[] serialize(Object obj) {
21        ByteArrayOutputStream byteOutputStream = null;
22        ObjectOutputStream objectOutputStream = null;
23
24        try {
25            byteOutputStream = new ByteArrayOutputStream();
26            objectOutputStream = new ObjectOutputStream(byteOutputStream);
27
28            objectOutputStream.writeObject(obj);
29            objectOutputStream.flush();
30
31            return byteOutputStream.toByteArray();
32        } catch (Exception e) {
33            e.printStackTrace();
34        } finally {
35            if (null != objectOutputStream) {
36                try {
37                    objectOutputStream.close();
38                    byteOutputStream.close();
39                } catch (Exception e) {
40                    e.printStackTrace();
41                }
42            }
43        }
44
45        return null;
46    }
47
48
49    /**
50     * 反序列化
51     * @param bytes
52     * @return
53     */
54    public static Object unserialize(byte[] bytes) {
55        ByteArrayInputStream byteInputStream = null;
56        ObjectInputStream objectInputStream = null;
57
58        try {
59            byteInputStream = new ByteArrayInputStream(bytes);
60            objectInputStream = new ObjectInputStream(byteInputStream);
61
62            return objectInputStream.readObject();
63
64        } catch (Exception e) {
65            e.printStackTrace();
66        } finally {
67            if (null != objectInputStream) {
68                try {
69                    objectInputStream.close();
70                    byteInputStream.close();
71                } catch (Exception e) {
72                    e.printStackTrace();
73                }
74            }
75        }
76        return null;
77    }
78
79}
80

 

给TA打赏
共{{data.count}}人
人已打赏
安全运维

OpenSSH-8.7p1离线升级修复安全漏洞

2021-10-23 10:13:25

安全运维

设计模式的设计原则

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索