redis的安装和测试
转载: https://www.cnblogs.com/maxm/p/6729553.html
redis一直都是调用别人部署好的,近日想要自己从灵开始搭建一次。其中也生出不少枝节,与各位猿友共同分享,望少走些弯路!
1.提前准备的资源
redis安装包(本人上传到csdn不需积分即可下载):
http://download.csdn.net/detail/u012580998/9818185
2.将安装包解压到 /opt/redis下(目录自定义,但是请容易记一些),然后进入到该目录
3.编译redis
执行命令如下:
(编译)
make
(进入src)
cd src
(安装,以及安装路径)
make install PREFIX=/usr/local/redis
4.将配置文件移动到/usr/local/redis目录
5.启动redis服务
执行
/usr/local/redis/bin/redis-server /usr/local/redis/redis-conf
6.修改配置文件
编辑redis.conf
将daemonize的值改为yes (这是后台运行)
bind 127.0.0.1 (只能本机访问)
改为
bind 0.0.0.0 (非本机亦可访问(或者可以绑定指定IP))
7.注意事项,个人安装测试过程中遇到问题以及解决方案
7.1编译过程中make 报错
解决办法:yum install tcl (也就是yum安装tcl)
7.2 远程访问失败
解决方案便是第六步,将bind 127.0.0.1 改成了 bind 0.0.0.0
否则redis只能本地访问
7.3 redis安全模式访问
测试程序报错为:
DENIED Redis is running protected mode because protected mode is enabled,
no bind address was specified, no authentication password is requested to clients.
In this mode connections are only accepted from the loopback interface.
需要给redis配置密码
启动redis客户端
执行 redis-cli指令
然后执行
config set requirepass 123456(密码)
8.附上测试代码(请新建Java项目,并引入jedis的jar包(百度一下就可以找到了))
import redis.clients.jedis.Jedis;import redis.clients.jedis.exceptions.JedisConnectionException;
public class RedisTest { private Jedis jedis = null; private String key1 = "key1"; private String key2 = "key2"; public RedisTest() { jedis = new Jedis("127.0.0.1"); // redis的IP地址 jedis.auth("redis"); // redis密码 } public static void main(String[] args) { RedisTest redisTest = new RedisTest(); redisTest.isReachable(); // redis是否访问成功 返回结果true/false redisTest.testData(); // 数据测试 redisTest.delData(); // 删除数据 redisTest.testExpire(); } public boolean isReachable() { boolean isReached = true; try { jedis.connect(); jedis.ping(); // jedis.quit(); } catch (JedisConnectionException e) { e.printStackTrace(); isReached = false; } System.out .println("The current Redis Server is Reachable:" + isReached); return isReached; } public void testData() { jedis.set("key1", "data1"); jedis.set("maxm", "MMM"); System.out.println(jedis.get("maxm")); System.out.println("Check status of data existing:" + jedis.exists(key1)); System.out.println("Get Data key1:" + jedis.get("key1")); long s = jedis.sadd(key2, "data2"); System.out.println("Add key2 Data:" + jedis.scard(key2) + " with status " + s); } public void delData() { long count = jedis.del(key1); System.out.println("Get Data Key1 after it is deleted:" + jedis.get(key1)); } public void testExpire() { long count = jedis.expire(key2, 5); try { Thread.currentThread().sleep(6000); } catch (InterruptedException e) { e.printStackTrace(); } if (jedis.exists(key2)) { System.out .println("Get Key2 in Expire Action:" + jedis.scard(key2)); } else { System.out.println("Key2 is expired with value:" + jedis.scard(key2)); } } }