数据库多样性
类型:
访问模式决定采用哪种数据库,同步的问题
关系型: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)
------------------------------------------
设置键值对
set k v
取值
get k
一次多个键,multiple
mset k1 v1 k2 v2 ...
mget k1 k2 ...
调试命令:
查找符合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)); } }