Redis的Java客户端使用的是Jedis
相关网博客和网站
redis入门学习网站(菜鸟教程) 地址:http://www.runoob.com/redis/redis-tutorial.html
Redis的Java客户端Jedis的八种调用方式(事务、管道、分布式)介绍 地址:https://my.oschina.net/sphl520/blog/312514
一致性哈希算法原理了解: 地址:http://blog.csdn.net/sparkliang/article/details/5279393
Java 使用 Redis
详情参见:http://www.runoob.com/redis/redis-java.html
import redis.clients.jedis.Jedis;
public class RedisListJava {
public static void main(String[] args) {
Jedis jedis =
new Jedis(
"localhost");
System.
out.println(
"Connection to server sucessfully");
jedis.lpush(
"tutorial-list",
"Redis");
jedis.lpush(
"tutorial-list",
"Mongodb");
jedis.lpush(
"tutorial-list",
"Mysql");
List<String> list = jedis.lrange(
"tutorial-list",
0 ,
5);
for(
int i=
0; i<list.size(); i++) {
System.
out.println(
"Stored string in redis:: "+list.
get(i));
}
}
}
ShardedJedisPool的使用
1 package com.test;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import redis.clients.jedis.JedisPoolConfig;
7 import redis.clients.jedis.JedisShardInfo;
8 import redis.clients.jedis.ShardedJedis;
9 import redis.clients.jedis.ShardedJedisPool;
10
11 public class RedisShardPoolTest {
12
13 static ShardedJedisPool pool;
14
15 static{
16 JedisPoolConfig config =
new JedisPoolConfig();
17 config.setMaxActive(
500);
18 config.setMaxIdle(
1000 *
60);
19 config.setMaxWait(
1000 *
10);
20 config.setTestOnBorrow(
true);
21 String hostA =
"192.168.0.100";
22 int portA =
6379;
23 String hostB =
"192.168.0.115";
24 int portB =
6379;
25 List<JedisShardInfo> jdsInfoList =
new ArrayList<JedisShardInfo>(
2);
26 JedisShardInfo infoA =
new JedisShardInfo(hostA, portA);
27 infoA.setPassword(
"admin");
28 JedisShardInfo infoB =
new JedisShardInfo(hostB, portB);
29 infoB.setPassword(
"admin");
30 jdsInfoList.add(infoA);
31 jdsInfoList.add(infoB);
32 pool =
new ShardedJedisPool(config, jdsInfoList);
33 }
34
35
36
37 /**
38
39 * @param args
40
41 */
42
43 public static void main(String[] args) {
44 for(
int i=
0; i<
100; i++){
45 String key = generateKey();
46 ShardedJedis jds =
null;
47 try {
48 jds = pool.getResource();
49 System.out.println(key+
":"+jds.getShard(key).getClient().getHost());
50 System.out.println(jds.set(key,Math.random()+
""));
51 }
catch (Exception e) {
52 e.printStackTrace();
53 }
finally {
54 pool.returnResource(jds);
55 }
56 }
57 }
58
59 private static int index =
1;
60 public static String
generateKey(){
61 return String.valueOf(Thread.currentThread().getId())+
"_"+(index++);
62 }
63 }
转载请注明原文地址: https://ju.6miu.com/read-700089.html