-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRedisClient.java
More file actions
85 lines (66 loc) · 2.3 KB
/
RedisClient.java
File metadata and controls
85 lines (66 loc) · 2.3 KB
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
package singularity.redis;
import lombok.Getter;
import lombok.Setter;
import redis.clients.jedis.Jedis;
import singularity.configs.given.GivenConfigs;
import singularity.configs.given.RedisConfigHandler;
import singularity.utils.MessageUtils;
import java.util.Optional;
import java.util.function.Consumer;
public class RedisClient {
public static RedisConfigHandler getConfig() {
return GivenConfigs.getRedisConfig();
}
@Getter @Setter
private static Jedis jedisClient;
public static String getHost() {
return getConfig().getHost();
}
public static int getPort() {
return getConfig().getPort();
}
public static String getUsername() {
return getConfig().getUsername();
}
public static String getPassword() {
return getConfig().getPassword();
}
public static boolean isEnabled() {
return getConfig().isEnabled();
}
public static Jedis getJedis() {
if (! isEnabled()) return null;
if (getJedisClient() != null) {
return getJedisClient();
}
Jedis jedis = new Jedis(getHost(), getPort());
String auth = jedis.auth(getUsername(), getPassword());
if (auth != null) {
if (auth.equals("OK")) {
MessageUtils.logInfo("Redis authenticated successfully.");
} else {
MessageUtils.logInfo("Redis authentication failed: " + auth);
}
}
String pingResponse = jedis.ping();
MessageUtils.logInfo("Redis ping response: " + pingResponse);
setJedisClient(jedis);
return getJedisClient();
}
public static void withJedis(Consumer<Jedis> consumer) {
withJedis(consumer, true);
}
public static void withJedis(Consumer<Jedis> consumer, boolean silent) {
if (isEnabled()) Optional.ofNullable(getJedis()).ifPresentOrElse(consumer, () -> {
if (! silent) {
MessageUtils.logWarning("Redis client is not initialized. Please check your Redis configuration.");
}
});
}
public static RedisClient getInstance() {
return GivenConfigs.getRedisClient();
}
public static void sendMessage(RedisMessage message) {
withJedis(j -> j.publish(message.getChannel(), message.getMessage()));
}
}