Created
January 25, 2017 19:43
-
-
Save mp911de/186fd77c30a36973429e4e9e77e886a4 to your computer and use it in GitHub Desktop.
Static held RedisClient, see https://groups.google.com/forum/#!topic/lettuce-redis-client-users/LZUYva9ny6k
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.example; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| import com.lambdaworks.redis.RedisClient; | |
| import com.lambdaworks.redis.RedisURI; | |
| import com.lambdaworks.redis.api.StatefulConnection; | |
| import com.lambdaworks.redis.api.StatefulRedisConnection; | |
| /** | |
| * @author Mark Paluch | |
| */ | |
| public class RedisConnector { | |
| // Static reference. A managed instance (some container like Spring, EJB or CDI would work | |
| // better with the application lifecyle). | |
| private final static RedisConnector connector = new RedisConnector(); | |
| private final RedisClient redisClient; | |
| private final List<StatefulRedisConnection<String, String>> connections = new ArrayList<>(); | |
| private RedisConnector() { | |
| this.redisClient = RedisClient.create(); | |
| Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown, "RedisConnector-ShutdownHook")); | |
| } | |
| /** | |
| * Static accessor. | |
| * | |
| * @return | |
| */ | |
| public static RedisConnector getInstance() { | |
| return connector; | |
| } | |
| /** | |
| * Initialize a connection. | |
| * | |
| * @param config | |
| */ | |
| public void connect(Config config) { | |
| RedisURI redisUri = RedisURI.Builder.redis(config.getEndpoint(), config.getPort()).withSsl(true) | |
| .withPassword(config.getCredentials()).build(); | |
| connections.add(redisClient.connect(redisUri)); | |
| } | |
| /** | |
| * Set a key-value pair. | |
| * | |
| * @param key | |
| * @param value | |
| */ | |
| public void set(String key, String value) { | |
| connections.stream().map(StatefulRedisConnection::sync).forEach(sync -> sync.set(key, value)); | |
| } | |
| /** | |
| * Cleanup resources. | |
| */ | |
| private void shutdown() { | |
| connections.forEach(StatefulConnection::close); | |
| redisClient.shutdown(); | |
| } | |
| // just for compile reasons | |
| static class Config { | |
| public String getEndpoint() { | |
| return null; | |
| } | |
| public int getPort() { | |
| return 0; | |
| } | |
| public String getCredentials() { | |
| return null; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment