虽然没有用到,但是看起来比Jedis强一些,这里写下示例,后续使用到再封装。
我把测试的代码整体放入。后续自己剥离吧,现在做个记录。哨兵连接设置下RedisURI的api即可。
public class TestLettuce {
private static RedisConnectionPool<RedisAsyncCommands<String,String>> pool = null;
private static final String REDIS_HOST="10.0.2.52";
private static final int REDIS_PORT =6379;
private static final int REDIS_EXPIRE=1;
private static final int REDIS_MAX_IDLE =20;
private static final int REDIS_MAX_ACTIVE=30;
static{
RedisURI redisURI=new RedisURI();
redisURI.setHost(REDIS_HOST);
redisURI.setPort(REDIS_PORT);
// redisURI.setPassword("");
//redisURI.setTimeout(REDIS_EXPIRE);
redisURI.setUnit(TimeUnit.SECONDS);
//redisURI.setPassword();
//redisURI.setDatabase();
// 也可直接将url的字符串传入 RedisClient.create()方法中
// eg:redis://[password@]host[:port][/databaseNumber]
RedisClient client=RedisClient.create(redisURI);
// 从redis客户端中获取一个异步的redis缓冲池
pool=client.asyncPool(REDIS_MAX_IDLE,REDIS_MAX_ACTIVE);
// 参数说明:REDIS_MAX_IDLE 为本缓冲池中最大闲置连接数量 // REDIS_MAX_ACTIVE为本缓冲池中最大活动连接数量
}
// 从缓冲池中获取一个连接
public static RedisAsyncCommands<String,String> getRedisConnection() {
return pool.allocateConnection();
}
// 关闭服务器时 关闭缓冲池
public static void shutDown() {
pool.close();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(4);
CountDownLatch latch = new CountDownLatch(4);
Long start = System.currentTimeMillis();
for (int i = 0; i < 4; i++) {
executor.execute(new Task1(pool,latch));
}
latch.await();
Long end = System.currentTimeMillis();
System.out.println("total :" + (end - start));
executor.shutdown();
}
}
class Task1 extends Thread {
RedisConnectionPool<RedisAsyncCommands<String, String>> pool;
CountDownLatch latch;
public Task1(RedisConnectionPool<RedisAsyncCommands<String, String>> pool, CountDownLatch latch) {
this.pool = pool;
this.latch = latch;
}
@Override
public void run() {
try {
for (int i = 0; i < 25000; i++) {
try {
RedisAsyncCommands<String, String> commads = pool.allocateConnection();
RedisFuture<String> future = commads.get("aa");
String str = future.get();
commads.close();
//System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
latch.countDown();
}
}
}
依赖:
<dependency> <groupId>biz.paluch.redis</groupId> <artifactId>lettuce</artifactId> <version>4.4.6.Final</version> </dependency>