Redis学习笔记

1 安装

$ wget http://download.redis.io/releases/redis-3.0.7.tar.gz
$ tar xzf redis-3.0.7.tar.gz
$ cd redis-3.0.7
$ make

网页下载地址:http://www.redis.cn/download.html

2 启动服务端

$ src/redis-server

3 启动客户端

You can interact with Redis using the built-in client:

$ src/redis-cli
redis> set foo bar
OK
redis> get foo
“bar”

数据类型:

类型常量 对象的名称 TYPE命令输出值
REDIS_STRING 字符串对象 “string”
REDIS_LIST 列表对象 “list”
REDIS_HASH 哈希对象 “hash”
REDIS_SET 集合对象 “set”
REDIS_ZSET 有序集合对象 “zset”

常用命令:

1 自增(原子操作)

SET connections 10
INCR connections => 11
INCR connections => 12
DEL connections
INCR connections => 1

对应的为DECR。
增加指定数字:INCRBY,对应的为DECRBY。

2 设置失效时间

SET resource:lock "Redis Demo"
EXPIRE resource:lock 120
resource:lock将在120s内被删除

获取距离失效的时间

TTL resource:lock

3 list

RPUSH puts the new value at the end of the list.

RPUSH friends "Alice"
RPUSH friends "Bob"

LPUSH puts the new value at the start of the list.

LPUSH friends “Sam”

LPOP、RPOP为移除列表的第一个/最后一个元素。

LRANGE gives a subset of the list. It takes the index of the first element you want to retrieve as its first parameter and the index of the last element you want to retrieve as its second parameter. A value of -1 for the second parameter means to retrieve elements until the end of the list.

LRANGE friends 0 -1 => 1) "Sam", 2) "Alice", 3) "Bob"
LRANGE friends 0 1 => 1) "Sam", 2) "Alice"
LRANGE friends 1 2 => 1) "Alice", 2) “Bob"

LLEN returns the current length of the list.

LLEN friends => 3

LPOP removes the first element from the list and returns it.

LPOP friends => "Sam"

RPOP removes the last element from the list and returns it.

RPOP friends => "Bob"

Note that the list now only has one element:

LLEN friends => 1
LRANGE friends 0 -1 => 1) "Alice"

4 set

SADD adds the given value to the set.

SADD superpowers "flight"
SADD superpowers "x-ray vision"
SADD superpowers "reflexes"

SREM removes the given value from the set.

SREM superpowers “reflexes"

SCARD myset => 4 (set中元素个数)
SINTER //返回两个或多个set的交集

SISMEMBER tests if the given value is in the set. It returns 1 if the value is there and 0 if it is not.

SISMEMBER superpowers "flight" => 1
SISMEMBER superpowers "reflexes" => 0

SMEMBERS returns a list of all the members of this set.

SMEMBERS superpowers => 1) "flight", 2) "x-ray vision"

SUNION combines two or more sets and returns the list of all elements.

SADD birdpowers "pecking"
SADD birdpowers "flight"
SUNION superpowers birdpowers => 1) "pecking", 2) "x-ray vision", 3) “flight”

SPOP //移除并返回列表中的一个随机元素
ZCOUNT //计算在有序集合中指定区间分数的成员数

5 zset

Sets are a very handy data type, but as they are unsorted they don’t work well for a number of problems. This is why Redis 1.2 introduced Sorted Sets.

A sorted set is similar to a regular set, but now each value has an associated score. This score is used to sort the elements in the set.

ZADD hackers 1940 "Alan Kay"
ZADD hackers 1906 "Grace Hopper"
ZADD hackers 1953 "Richard Stallman"
ZADD hackers 1965 "Yukihiro Matsumoto"
ZADD hackers 1916 "Claude Shannon"
ZADD hackers 1969 "Linus Torvalds"
ZADD hackers 1957 "Sophie Wilson"
ZADD hackers 1912 "Alan Turing"

In these examples, the scores are years of birth and the values are the names of famous hackers.

ZRANGE hackers 2 4 => 1) "Claude Shannon", 2) "Alan Kay", 3) "Richard Stallman”
ZSCORE //获取元素的score值

6 hset

Simple strings, sets and sorted sets already get a lot done but there is one more data type Redis can handle: Hashes.

Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (eg: A User with a number of fields like name, surname, age, and so forth):

HSET user:1000 name "John Smith"
HSET user:1000 email "john.smith@example.com"
HSET user:1000 password "s3cret"

To get back the saved data use HGETALL:

HGETALL user:1000

You can also set multiple fields at once:

HMSET user:1001 name "Mary Jones" password "hidden" email "mjones@example.com"

If you only need a single field value that is possible as well:

HGET user:1001 name => "Mary Jones”

PUBSUB

redis是一个基于key-value的存储系统,但同样提供了许多其他的使用的组件,比如SUBSCRIBE、PUBLISH这两个命令。这两个命令能让你非常方便地再两个进程中进行通信。

订阅/发布/取消订阅
SUBSCRIBE、PUBLISH、UNSUBSCRIBE

# SUBSCRIBE 订阅给定的一个或多个频道的信息 SUBSCRIBE channel1 channel2
127.0.0.1:6379> SUBSCRIBE channel1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "channel1"
3) (integer) 1

# PUBLISH 将信息发送到指定的频道 PUBLISH CHANNEL MESSAGE 返回值为订阅该频道的客户端数量
127.0.0.1:6379> PUBLISH channel1 message1
(integer) 1

事务

Redis事务让一组命令在单个步骤执行。事务中有两个属性,说明如下:
在一个事务中的所有命令按顺序执行作为单个隔离操作。通过另一个客户端发出的请求在Redis的事务的过程中执行,这是不可能的。
Redis的事务具有原子性。原子意味着要么所有的命令都执行或都不执行。
Redis的事务由指令多重发起,然后需要传递在事务,而且整个事务是通过执行命令EXEC执行命令列表。

redis 127.0.0.1:6379> MULTI
OK
List of commands here
redis 127.0.0.1:6379> EXEC

Java连接Redis

首先需要下载jedis.jar,将其加入类路径,或者添加maven依赖。

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.1</version>
</dependency>

代码示例如下:

import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;

public class TestRedis {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost");
        print(jedis.ping());
        print();

        jedis.set("name", "lee");
        print(jedis.get("name"));
        print();

        jedis.lpush("vector", "bbb");
        jedis.lpush("vector", "aaa");
        jedis.rpush("vector", "ccc");
        List<String> list = jedis.lrange("vector", 0, -1);
        for (int i = 0; i < list.size(); i++) {
            print(list.get(i));
        }
        print();

        jedis.hset("person1", "name", "Lee");
        jedis.hset("person1", "age", "12");
        jedis.hset("person1", "address", "beijing");

        Map<String, String> mymap = jedis.hgetAll("person1");
        for (Map.Entry<String, String> entry : mymap.entrySet()) {
            print(entry.getKey() + " " + entry.getValue());
        }
    }

    public static void print(Object...objects) {
        for (Object obj: objects) {
            System.out.print(obj.toString() + " ");
        }
        System.out.println();
    }
}

转载:http://blog.csdn.net/foreverling/article/details/50960640

时间: 2016-05-18
Tags: redis

Redis学习笔记的相关文章

redis 学习笔记(6)-cluster集群搭建

上次写redis的学习笔记还是2014年,一转眼已经快2年过去了,在段时间里,redis最大的变化之一就是cluster功能的正式发布,以前要搞redis集群,得借助一致性hash来自己搞sharding,现在方便多了,直接上cluster功能就行了,而且还支持节点动态添加.HA.节点增减后缓存重新分布(resharding). 下面是参考官方教程cluster-tutorial 在mac机上搭建cluster的过程: 一.下载最新版redis 编译 目前最新版是3.0.7,下载地址:http:

Redis学习笔记~StackExchange.Redis实现分布式Session

对于多WEB的环境现在已经是必须的了,很难想像一台WEB服务器面对百万并发的响应,所以,我们需要多台WEB服务器集群合作,来缓解这种高并发,高吞吐的场景,而对于多WEB的场景又会有个问题出现,即session存储的问题,如一个用户登陆后,把一个状态信息存储到当前WEB服务器的session里,而你请求其它页面时,很可能就被路由到另一台服务器了,这时,session也就丢了,而对于这种情况,有人把redis这个存储中间件想了起来,对它进行了封装,就有了今天基于redis的session共享机制.

redis 学习笔记(7)-cluster 客户端(jedis)代码示例

上节学习了cluster的搭建及redis-cli终端下如何操作,但是更常用的场景是在程序代码里对cluster读写,这需要redis-client对cluster模式的支持,目前spring-data-redis(1.6.4)还不支持cluster,最新的1.7.0 RC1已经有cluster的相关实现了,不过目前尚未正式发布,所以现阶段要使用redis-cluster的话,client最好还是选用原生的jedis,示例代码如下: 配置文件: <?xml version="1.0&quo

redis 学习笔记(5)-Spring与Jedis的集成

首先不得不服Spring这个宇宙无敌的开源框架,几乎整合了所有流行的其它框架,http://projects.spring.io/spring-data/从这上面看,当下流行的redis.solr.hadoop.mongoDB.couchBase... 全都收入囊中.对于redis整合而言,主要用到的是spring-data-redis 使用步骤: 一.pom添加依赖项 <dependency> <groupId>org.springframework.data</group

redis学习笔记之常用命令(基础篇)

以下是redis命令行下的一些常用的基础命令,可以供大家参考学习: 1.[ set key value ] 存入一个key和值.如:set myname reson 2.[ get key ] 读取一个key的值. 3.[ del key ] 删除一个key. 4.[ del key1 key2 ... keyN ] 删除多个key.如:del myname1 myname2 5.[ exists key ] 判断一个key是否存在. 6.[ type key ] 查看key的类型. 7.[ r

redis 学习笔记(4)-HA高可用方案Sentinel配置

上一节中介绍了master-slave模式,在最小配置:master.slave各一个节点的情况下,不管是master还是slave down掉一个,"完整的"读/写功能都将受影响,这在生产环境中显然不能接受.幸好redis提供了sentinel(哨兵)机制,通过sentinel模式启动redis后,自动监控master/slave的运行状态,基本原理是:心跳机制+投票裁决 每个sentinel会向其它sentinal.master.slave定时发送消息,以确认对方是否"活

redis 学习笔记(3)-master/slave(主/从模式)

类似mysql的master-slave模式一样,redis的master-slave可以提升系统的可用性,master节点写入cache后,会自动同步到slave上. 环境: master node: 10.6.144.155:7030 slave node: 10.6.144.156:7031   一.配置 仅需要在slave node上修改配置: 找到slaveof这行,参考下面的修改(填上master node的Ip和端口就完事了) slaveof 10.6.144.155 7030 另

php redis学习笔记

1,connect 描述:实例连接到一个Redis. 参数:host: string,port: int 返回值:BOOL 成功返回:TRUE;失败返回:FALSE <?php $redis = new redis(); $result = $redis->connect('127.0.0.1', 6379); var_dump($result); //结果:bool(true) ?> 2,set 描述:设置key和value的值 参数:Key Value 返回值:BOOL 成功返回:T

redis 学习笔记(2)-client端示例代码

redis提供了几乎所有主流语言的client,java中主要使用二种:Jedis与Redisson 一.Jedis的使用 1 <dependency> 2 <groupId>redis.clients</groupId> 3 <artifactId>jedis</artifactId> 4 <version>2.6.0</version> 5 <type>jar</type> 6 <scop