Jedis操作Redis数据库

添加Maven依赖:

 1     <dependencies>
 2         <!-- 单元测试 -->
 3         <dependency>
 4             <groupId>junit</groupId>
 5             <artifactId>junit</artifactId>
 6             <version>4.11</version>
 7             <scope>test</scope>
 8         </dependency>
 9         <dependency>
10             <groupId>redis.clients</groupId>
11             <artifactId>jedis</artifactId>
12             <version>2.8.0</version>
13         </dependency>
14     </dependencies>

联系Jedis操作redis的常用命令:

TestRedis.java

  1  import java.util.List;
  2  import org.junit.Test;
  3  import redis.clients.jedis.Jedis;
  4  import redis.clients.jedis.JedisPool;
  5  import redis.clients.jedis.JedisPoolConfig;
  6  import redis.clients.jedis.Pipeline;
  7  import redis.clients.jedis.Transaction;
  8  
  9  public class TestRedis {
 10      
 11      String host = "192.168.1.99";
 12      int port = 6379;
 13      Jedis jedis = new Jedis(host, port);
 14      /**
 15       * 单机单链接的方式
 16       * 这种获取连接的方式只在测试的时候使用
 17       * 注意需要关闭redis服务器的防火墙
 18       * @throws Exception
 19       */
 20      @Test
 21      public void test1() throws Exception {
 22          //获取redis连接
 23          //jedis.set("hehe", "aaaaaa");
 24          String value = jedis.get("hehe");
 25          System.out.println(value);
 26          jedis.close();
 27      }
 28      
 29      /**
 30       * 单机连接池方式
 31       * 实际工作中建议使用这种方式
 32       * @throws Exception
 33       */
 34      @Test
 35      public void test2() throws Exception {
 36          //指定连接池的参数
 37          JedisPoolConfig poolConfig = new JedisPoolConfig();
 38          //最大空闲连接数
 39          poolConfig.setMaxIdle(10);
 40          //连接池的最大连接数
 41          poolConfig.setMaxTotal(100);
 42          //设置获取连接的最大等待时间
 43          poolConfig.setMaxWaitMillis(1000);
 44          //从连接池中获取连接的时候是否需要校验,这样可以保证取出的连接都是可用的
 45          poolConfig.setTestOnBorrow(true);
 46          //获取jedis连接池
 47          JedisPool jedisPool = new JedisPool(poolConfig , host, port);
 48          //从连接池中取一个链接
 49          Jedis jedis = jedisPool.getResource();
 50          String value = jedis.get("hehe");
 51          System.out.println(value);
 52          //这个close并不是关闭连接,而是把连接还给连接池。
 53          jedis.close();
 54      }
 55      
 56      /**
 57       * 手工实现incr命令
 58       * @throws Exception
 59       */
 60      @Test
 61      public void testIncr() throws Exception {
 62         //监控键a的值,如果在事务开启(multi命令执行之间这个键的值被其他命令修改了
 63         //watch并不能取消其他线程的修改那么就会取消事务代码的执行,事务会返回一个null(nil))
 64          jedis.watch("a");
 65          String value = jedis.get("a");
 66          int parseInt = Integer.parseInt(value);
 67          parseInt++;
 68          System.out.println("休息一会....");
 69          Thread.sleep(5000);
 70          Transaction multi = jedis.multi();
 71          multi.set("a", parseInt+"");
 72          List<Object> exec = multi.exec();
 73          if(exec==null){//exec返回的是null说明键的值被其它线程修改了.
 74              System.out.println("值被修改了,事务没有执行。。。。");
 75              testIncr();
 76          }else{
 77              System.out.println("正常执行....");
 78          }
 79      }
 80      
 81      /**
 82       * 模拟恶意登陆的场景,
 83       * 限制一个IP的访问次数
 84       */     
 85      private boolean testLogin(String ip) {
 86          String value = jedis.get(ip);
 87          if(value==null){
 88              jedis.set(ip, 1+"");
 89              jedis.expire(ip, 60);//如果不加这个设置这个ip只能访问10次
 90          }else{
 91              int parseInt = Integer.parseInt(value);
 92              if(parseInt>10){
 93                  System.out.println("访问受限!");
 94                  return false;
 95              }
 96              jedis.incr(ip);
 97          }
 98          
 99          return true;
100      }
101      
102      /**
103       * 不使用管道
104       * 初始化1000条数据
105       * 消耗时间:5365(老师机器)  122(我的机器)
106       * @throws Exception
107       */
108      @Test
109      public void test3() throws Exception {
110          long start_time = System.currentTimeMillis();
111          for(int i=0;i<1000;i++){
112              jedis.set("he"+i, "hello");
113          }
114          System.out.println("消耗时间:"+(System.currentTimeMillis()-start_time));
115      }
116      
117      
118      /**
119       * 使用管道
120       * 初始化1000条数据
121       * 消耗时间:281(老师机器) 27(我的机器)
122       * @throws Exception
123       */
124      @Test
125      public void test4() throws Exception {
126          long start_time = System.currentTimeMillis();
127          Pipeline pipelined = jedis.pipelined();
128          for(int i=0;i<1000;i++){
129              pipelined.set("ha"+i, "hello");
130          }
131          
132          pipelined.sync();//执行管道中的命令
133          System.out.println("消耗时间:"+(System.currentTimeMillis()-start_time));
134      }
135  }

 一般通过一个工具类来从redis连接池中获得redis连接.

 RedisUtil.java

 1 import redis.clients.jedis.Jedis;
 2 import redis.clients.jedis.JedisPool;
 3 import redis.clients.jedis.JedisPoolConfig;
 4 
 5 /**
 6  * 静态工具类
 7  * @author Administrator
 8  *
 9  */
10 public class RedisUtils {
11     
12     private static JedisPool jedisPool = null;
13     
14     /**
15      * 从连接池中获取一个redis链接
16      * 如果两个线程,第一个线程先进来还没有new出来,第二个线程进入if了,这样就造
17      * 线程的安全性问题.
18      * @return
19      */
20     public static synchronized Jedis getJedis(){
21         if(jedisPool==null){//第一次初始化的时候是null,第一次出事后之后就不再执行
22             JedisPoolConfig poolConfig = new JedisPoolConfig();
23             //最大空闲连接数
24             poolConfig.setMaxIdle(10);
25             //连接池中最大连接数
26             poolConfig.setMaxTotal(100);
27             //在获取链接的时候设置的超市时间
28             poolConfig.setMaxWaitMillis(1000);
29             //表示在向连接池中创建连接的时候会对链接进行测试,保证连接池中的链接都是可用的。
30             poolConfig.setTestOnBorrow(true);
31             jedisPool = new JedisPool(poolConfig, "192.168.1.170", 6379);
32         }
33         Jedis jedis = jedisPool.getResource();
34         return jedis;
35     }
36     
37     /**
38      * 把redis链接返回连接池
39      */
40     public static void returnJedis(Jedis jedis){
41         jedisPool.returnResourceObject(jedis);
42     }
43 }

通过Jedis来操作Redis集群.

ClusterTest.java

 1 import java.util.HashSet;
 2 import java.util.Set;
 3 
 4 import org.junit.Test;
 5 
 6 import redis.clients.jedis.HostAndPort;
 7 import redis.clients.jedis.JedisCluster;
 8 import redis.clients.jedis.JedisPoolConfig;
 9 
10 public class ClusterTest {
11     
12     
13     @Test
14     public void test() throws Exception{
15         JedisPoolConfig poolConfig = new JedisPoolConfig();
16         //最大空闲连接数
17         poolConfig.setMaxIdle(10);
18         //连接池中最大连接数
19         poolConfig.setMaxTotal(100);
20         //在获取链接的时候设置的超市时间
21         poolConfig.setMaxWaitMillis(1000);
22         //表示在向连接池中创建连接的时候会对链接进行测试,保证连接池中的链接都是可用的。
23         poolConfig.setTestOnBorrow(true);
24         Set<HostAndPort> nodes = new HashSet<HostAndPort>();
25         nodes.add(new HostAndPort("192.168.0.172", 7000));
26         nodes.add(new HostAndPort("192.168.0.172", 7001));
27         nodes.add(new HostAndPort("192.168.0.172", 7002));
28         nodes.add(new HostAndPort("192.168.0.172", 7003));
29         nodes.add(new HostAndPort("192.168.0.172", 7004));
30         nodes.add(new HostAndPort("192.168.0.172", 7005));
31         
32         JedisCluster jedisCluster = new JedisCluster(nodes, poolConfig);
33         jedisCluster.set("a", "1");
34         String value = jedisCluster.get("a");
35         System.out.println(value);
36     }
37 }
原文地址:https://www.cnblogs.com/DreamDrive/p/5587137.html