• Redis从基础命令到实战之字符串类型


    字符串类型是Redis中最基本的数据类型,能存储任何形式的字符串和和二进制数据。本文以代码形式列举常用的操作命令,并在实践部分演示一个简单的商品管理功能,实现了通常使用关系型数据库开发的增改查功能,注意并没有实现删除功能,这将放在后面的列表类型中去实现。

    一、常用命令

    pom.xml

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. <dependencies>  
    2.     <dependency>  
    3.         <groupId>redis.clients</groupId>  
    4.         <artifactId>jedis</artifactId>  
    5.         <version>2.8.1</version>  
    6.     </dependency>  
    7.     <dependency>  
    8.         <groupId>com.alibaba</groupId>  
    9.         <artifactId>fastjson</artifactId>  
    10.         <version>1.2.8</version>  
    11.     </dependency>  
    12.     <dependency>  
    13.         <groupId>org.apache.commons</groupId>  
    14.         <artifactId>commons-lang3</artifactId>  
    15.         <version>3.4</version>  
    16.     </dependency>  
    17. </dependencies>  

    StringExample.java

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import java.util.Iterator;  
    2. import java.util.List;  
    3. import java.util.Set;  
    4.   
    5. import redis.clients.jedis.Jedis;  
    6.   
    7. public class StringExample {  
    8.   
    9.     public static void main(String[] args) {  
    10.         Jedis jedis = JedisProvider.getJedis();  
    11.         //清空数据库  
    12.         jedis.flushDB();  
    13.   
    14.         String key = "redis_str";  
    15.         //判断key是否存在  
    16.         boolean exists = jedis.exists(key);  
    17.         if (exists) {  
    18.             //删除key,返回实际删除的行数  
    19.             long l = jedis.del(key);  
    20.             print("del " + key + "=" + l);  
    21.         }  
    22.         //新增key,成功返回 OK  
    23.         String result = jedis.set(key, "a string value");  
    24.         print("set " + key + "=" + result);  
    25.         //读取value长度  
    26.         print("strlen(" + key + ")=" + jedis.strlen(key));  
    27.         //读取value  
    28.         String value = jedis.get(key);  
    29.         print("get " + key + "=" + value);  
    30.   
    31.         //设置过期时间为5秒  
    32.         jedis.expire(key, 5);  
    33.         //查看某个key的剩余生存时间,单位秒,永久生存或者不存在的都返回-1  
    34.         Long ttl = jedis.ttl(key);  
    35.         print("ttl of " + key + "=" + ttl);  
    36.         //移除某个key的生存时间  
    37.         jedis.persist(key);  
    38.         print("移除生存时间后 ttl of " + key + "=" + jedis.ttl(key));  
    39.         //查看key所储存的值的类型  
    40.         String type = jedis.type(key);  
    41.         print("type of " + key + "=" + type);  
    42.   
    43.         //一次性新增多个key  
    44.         jedis.mset("key001", "value001", "key002", "value002", "key003",  
    45.                 "value003", "key004", "value004");  
    46.         print("批量设置key: key001,key002,key003,key004");  
    47.           
    48.         //读取所有key,遍历,判断类型  
    49.         System.out.println("读取所有key并筛选string类型");  
    50.         Set<String> keys = jedis.keys("*");  
    51.         Iterator<String> it = keys.iterator();  
    52.         while (it.hasNext()) {  
    53.             key = it.next();  
    54.             if (jedis.type(key).equals("string"))  
    55.                 System.out.println("get " + key + "=" + jedis.get(key));  
    56.         }  
    57.         System.out.println("------------------------------------------------------");  
    58.         System.out.println();  
    59.           
    60.         //一次性获取多个key值  
    61.         System.out.println("批量读取key: key001,key002,key003,key004");  
    62.         List<String> list = jedis.mget("key001", "key002", "key003", "key004");  
    63.         for (int i = 0; i < list.size(); i++) {  
    64.             System.out.println(list.get(i));  
    65.         }  
    66.         System.out.println("------------------------------------------------------");  
    67.         System.out.println();  
    68.         //一次性删除多个key,返回成功删除个数  
    69.         Long del = jedis.del(new String[] { "key001", "key002" });  
    70.         print("[批量删除]del key001,key002=" + del);  
    71.   
    72.         // 禁止覆盖  
    73.         Long setnx = jedis.setnx("key003", "value003_new");  
    74.         print("[禁止覆盖]setnx key003 to value003_new=" + setnx + "; value=" + jedis.get("key003"));  
    75.   
    76.         //新增key同时设置有效期(秒)  
    77.         result = jedis.setex(key, 3, "setex demo");  
    78.         print("setex " + key + "(ttl 3)=" + result + "; value=" + jedis.get(key) + "; ttl=" + jedis.ttl(key));  
    79.         try {  
    80.             Thread.sleep(4000);  
    81.         } catch (InterruptedException e) {  
    82.         }  
    83.         print("[4秒之后]get " + key + "=" + jedis.get(key));  
    84.           
    85.         //获取原值, 更新为新值一步完成  
    86.         key = "key003";  
    87.         String former = jedis.getSet(key, "value002-after-getset");  
    88.         print("getSet 原值:" + former + "; 新值" + jedis.get(key));  
    89.   
    90.         //incr 自增  
    91.         key = "redis_num";  
    92.         jedis.del(key);  
    93.         long incr = jedis.incr(key);  
    94.         print("incr " + key + " = " + incr);  
    95.         incr = jedis.incr(key);  
    96.         print("incr " + key + " = " + incr);  
    97.         incr = jedis.incrBy(key, 100);  
    98.         print("incrBy " + key + " 100 = " + incr);  
    99.         Long decr = jedis.decrBy(key, 100);  
    100.         print("decrBy " + key + " 100 = " + decr);  
    101.   
    102.         jedis.close();  
    103.     }  
    104.   
    105.     private static void print(String info) {  
    106.         System.out.println(info);  
    107.         System.out.println("------------------------------------------------------");  
    108.         System.out.println();  
    109.     }  
    110. }  

    JedisProvider.java

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import redis.clients.jedis.Jedis;  
    2. import redis.clients.jedis.JedisPool;  
    3. import redis.clients.jedis.JedisPoolConfig;  
    4.   
    5. public class JedisProvider {  
    6.   
    7.     private static JedisPool pool;  
    8.       
    9.     public static Jedis getJedis() {  
    10.         if(pool == null) {  
    11.             JedisPoolConfig config = new JedisPoolConfig();  
    12.             config.setMaxTotal(1024);  
    13.             config.setMaxIdle(200);  
    14.             config.setMaxWaitMillis(1000);  
    15.             config.setTestOnBorrow(true);  
    16.             config.setTestOnReturn(true);  
    17.             pool = new JedisPool(config, "127.0.0.1", 6380);  
    18.         }  
    19.         return pool.getResource();  
    20.     }  
    21. }  

    二、实践练习

    StringLession.Java

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import java.util.ArrayList;  
    2. import java.util.List;  
    3.   
    4. import org.apache.commons.lang3.math.NumberUtils;  
    5.   
    6. import redis.clients.jedis.Jedis;  
    7.   
    8. public class StringLession {  
    9.   
    10.     public static void main(String[] args) {  
    11.         StringLession sl = new StringLession();  
    12.         sl.clear();  
    13.           
    14.         //添加一批商品  
    15.         for(int i = 0; i< 41; i++) {  
    16.             Goods goods = new Goods(0, "goods" + String.format("%05d", i), i);  
    17.             sl.addGoods(goods);  
    18.         }  
    19.         //读取商品总数  
    20.         System.out.println("商品总数: " + sl.getTotalCount());  
    21.         //分页显示  
    22.         List<Goods> list = sl.getGoodsList(2, 20);  
    23.         System.out.println("第二页商品:");  
    24.         for(Goods goods : list) {  
    25.             System.out.println(goods);  
    26.         }  
    27.     }  
    28.       
    29.     private Jedis jedis = null;  
    30.       
    31.     public StringLession() {  
    32.         this.jedis = JedisProvider.getJedis();  
    33.     }  
    34.   
    35.     /** 
    36.      * 获得一个自增主键值 
    37.      * @return 
    38.      */  
    39.     private long getIncrementId() {  
    40.         String key = "goods:count";  
    41.         return jedis.incr(key);  
    42.     }  
    43.       
    44.     /** 
    45.      * 添加一个商品 
    46.      * @param goods 
    47.      * @return 
    48.      */  
    49.     public boolean addGoods(Goods goods) {  
    50.         long id = getIncrementId();  
    51.         goods.setId(id);  
    52.         String key = "goods:" + id;  
    53.         return jedis.set(key, goods.toString()).equals("OK");  
    54.     }  
    55.       
    56.     /** 
    57.      * 修改商品 
    58.      * @param goods 
    59.      * @return 
    60.      */  
    61.     public boolean editGoods(Goods goods) {  
    62.         String key = "goods:" + goods.getId();  
    63.         if(jedis.exists(key)) {  
    64.             return jedis.set(key, goods.toString()).equals("OK");  
    65.         }  
    66.         return false;  
    67.     }  
    68.       
    69.     /** 
    70.      * 读取商品总数 
    71.      * @return 
    72.      */  
    73.     public long getTotalCount() {  
    74.         String key = "goods:count";  
    75.         return NumberUtils.toLong(jedis.get(key));  
    76.     }  
    77.       
    78.     /** 
    79.      * 读取用于分页的商品列表 
    80.      * @param pageIndex 页数 
    81.      * @param pageSize 每页显示行数 
    82.      * @return 
    83.      */  
    84.     public List<Goods> getGoodsList(int pageIndex, int pageSize) {  
    85.         int totals = (int)getTotalCount();  
    86.         int from = (pageIndex - 1) * pageSize;  
    87.         if(from < 0) {  
    88.             from = 0;  
    89.         }  
    90.         else if(from > totals) {  
    91.             from = (totals / pageSize) * pageSize;  
    92.         }  
    93.         int to = from + pageSize;  
    94.         if(to > totals) {  
    95.             to = totals;  
    96.         }  
    97.         String[] keys = new String[(int)(to - from)];  
    98.         for(int i = from; i < to; i++) {  
    99.             keys[i - from] = "goods:" + (i + 1);  
    100.         }  
    101.         List<String> list = jedis.mget(keys);  
    102.         List<Goods> goodsList = new ArrayList<>();  
    103.         for(String value : list) {  
    104.             goodsList.add(Goods.parseJson(value));  
    105.         }  
    106.         return goodsList;  
    107.     }  
    108.       
    109.     public void clear() {  
    110.         jedis.flushDB();  
    111.     }  
    112. }  

    Goods.java

    [java] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. import com.alibaba.fastjson.JSON;  
    2.   
    3. public class Goods {  
    4.   
    5.     public Goods() {}  
    6.       
    7.     public Goods(long id, String title, float price) {  
    8.         super();  
    9.         this.id = id;  
    10.         this.title = title;  
    11.         this.price = price;  
    12.     }  
    13.       
    14.     private long id;  
    15.     private String title;  
    16.     private float price;  
    17.     public long getId() {  
    18.         return id;  
    19.     }  
    20.     public void setId(long id) {  
    21.         this.id = id;  
    22.     }  
    23.     public String getTitle() {  
    24.         return title;  
    25.     }  
    26.     public void setTitle(String title) {  
    27.         this.title = title;  
    28.     }  
    29.     public float getPrice() {  
    30.         return price;  
    31.     }  
    32.     public void setPrice(float price) {  
    33.         this.price = price;  
    34.     }  
    35.       
    36.     public String toString() {  
    37.         return JSON.toJSONString(this);  
    38.     }  
    39.       
    40.     public static Goods parseJson(String json) {  
    41.         return JSON.parseObject(json, Goods.class);  
    42.     }  
    43. }  



  • 相关阅读:
    dpkg 删除 百度网盘 程序
    ubuntu 安装go
    解决 swap file “*.swp”already exists!问题
    ROS Topic 常用指令
    正交概念
    vim 永久显示行号 & 临时显示行号
    awk、grep、sed
    Keil中使用Astyel进行C语言的格式化
    红黑树学习
    802.11 对于multicast 和 broadcast的处理
  • 原文地址:https://www.cnblogs.com/sa-dan/p/6836859.html
Copyright © 2020-2023  润新知