1. 安装
brew install redis
==> Caveats
To have launchd start redis now and restart at login:
brew services start redis
Or, if you don't want/need a background service you can just run:
redis-server /usr/local/etc/redis.conf
- 在linux上,可以用apt-get,不再赘述。
2. 启动
brew services start redis
3. 客户端连接与测试
redis-cli
127.0.0.1:6379> set color "blue"
OK
127.0.0.1:6379> get color
"blue"
redis有自带的客户端,可以连接。
4. 配置密码
127.0.0.1:6379> config set requirepass "123456"
OK
127.0.0.1:6379> get color
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> get color
"blue"
redis默认执行指令是无需密码的,可以设置密码,设置后,每个session连接中,需要密码授权一次,才能执行之后的指令。
5. 使用Java测试
使用Java来测试一下Redis。
a. 首先maven中加入常用的Redis客户端包Jedis
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
b. 然后写一个测试类
public class Redis {
public static void main(String[] args) {
String key = "colors";
String password = "123456";
Jedis jedis = new Jedis("localhost");
jedis.auth(password);
jedis.lpush(key, "blue");
jedis.lpush(key, "yellow");
jedis.lpush(key, "red");
List<String> list = jedis.lrange(key, 0, jedis.llen(key) - 1);
Iterator iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
jedis.close();
}
}
c. 运行输出结果
red
yellow
blue