正如Jedis documentation所述,Jedis客户端不是线程安全的。
单个Jedis实例不是线程安全的!
所以我使用的是JedisPool。我想从服务器将数据推送到浏览器的WebSocket客户端。为此我使用的是Redis的PubSub机制。
@ServerEndpoint(value = "/websocket/{channelName}", configurator = GetHttpSessionConfigurator.class)
public class WSEndpoint {
private WSJedisPubSub wsJedisPubSub;
private static JedisPool jedisPool = null;
@OnOpen
public void onOpen(Session session,
@PathParam("channelName") String channelName) throws IOException,
EncodeException {
// FIXME proper synchronization is required here
if (jedisPool == null) {
initPool();
}
wsJedisPubSub = new WSJedisPubSub(session);
try (Jedis redisClient = jedisPool.getResource()) {
redisClient.subscribe(wsJedisPubSub, channelName);
}
private void initPool() {
JedisPoolConfig jedisConfiguration = new JedisPoolConfig();
jedisPool = new JedisPool(jedisConfiguration, "localhost", 6379);
}
}
我的应用程序可以连接数千个websockets。我怀疑跟随一段代码。
try (Jedis redisClient = jedisPool.getResource()) {
redisClient.subscribe(wsJedisPubSub, channelName);
}