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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM