Redis入門

數據庫多樣性java

類型:redis

訪問模式決定採用哪一種數據庫,同步的問題數據庫

關係型:Oracle MySQL ...,實時事務處理
文檔性:MongoDB,適合高聚合的數據結構
KV型:Redis,高速存放和查找,中間緩存
全文搜索:ElasticSearch Solor,輸入關鍵詞,不單單是String.contains,分詞...
分佈式:HBASE 大數據Hadoop HDFS緩存

-------------------------------------------數據結構

Map<K, V>
K key
V value分佈式

map.put(k, v)
map.get(k)oop

------------------------------------------大數據

設置鍵值對
set k v
取值
get k
一次多個鍵,multiple
mset k1 v1 k2 v2 ...
mget k1 k2 ...spa

調試命令:
查找符合pattern的全部key,*表示任意字符串
keys pattern 調試

指定有效期
TTL; time to live

設置鍵值對並指定有效期,單位秒
setex k ex v

將指定鍵的值+1
incr k
將指定鍵的值-1
decr k

刪除鍵值對
del k

 

  pom.xml

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

  ArticleService.java

package redistest;

import java.util.List;

import redis.clients.jedis.Jedis;

public class ArticleService {

    private Jedis jedis = new Jedis("localhost");
    
    public void add(long id, String title) {
        String key = titleKey(id); // article:1:title
        jedis.set(key, title);
    }

    private String titleKey(long id) {
        return "article:" + id + ":title";
    }
    
    public void upVote(long id) {
//        incr article:2:upvotes        
        jedis.incr(upvotesKey(id));
    }

    private String upvotesKey(long id) {
        return "article:" + id + ":upvotes";
    }

    public void downVote(long id) {
//        incr article:2:downvotes        
        jedis.incr(downvotesKey(id));
    }

    private String downvotesKey(long id) {
        return "article:" + id + ":downvotes";
    }

    public String info(long id) {
        List<String> values = jedis.mget(titleKey(id), 
                upvotesKey(id), downvotesKey(id));
        String title = values.get(0);
        String upvotes = values.get(1);
        String downvotes = values.get(2);
        
        return title + "#" + id + "[" + upvotes + ", " + downvotes + "]";
    }
}
ArticleServiceTest.java
package redistest;

public class ArticleServiceTest {
    public static void main(String[] args) {
        ArticleService service = new ArticleService();
        service.add(1L, "標題1");
        service.add(2L, "標題2");
        service.add(3L, "標題3");
        
//        for (int i = 0; i < 100; i++) {
//            service.upVote(2L);
//        }
        
        service.downVote(3L);
        
        System.out.println(service.info(1));
        System.out.println(service.info(2));
        System.out.println(service.info(3));
    }
}
相關文章
相關標籤/搜索