带你零基础入门redis【二】

本篇文章介绍redis如何设置开机自启动以及如何在java中应用

一、设置redis开机自启

1、修改redis配置

[root@VM_6_102_centos ~]# vim /usr/local/redis-3.2.8/redis.conf 

    ①、设置外网可以访问,将bind 127.0.0.1注释掉

    ②、Redis默认不是以守护进程的方式运行,将daemonize改为yes,启用守护进程(启动redis时不再有启动界面)

    ③、设置redis密码  requirepass Abc123_

2、编写启动脚本

[root@VM_6_102_centos src]# vim /etc/init.d/redis 

  粘贴下面的代码,注意修改路径(这段代码就是redis根目录 /utils/redis_init_script 启动脚本的代码)

 1 #!/bin/sh
 2 # chkconfig: 2345 10 90  
 3 # description: Start and Stop redis  
 4 
 5 REDISPORT=6379
 6 EXEC=/usr/local/redis-3.2.8/src/redis-server
 7 CLIEXEC=/usr/local/redis-3.2.8/src/redis-cli
 8 
 9 PIDFILE=/var/run/redis_${REDISPORT}.pid
10 CONF="/usr/local/redis-3.2.8/redis.conf"
11 
12 case "$1" in
13     start)
14         if [ -f $PIDFILE ]
15         then
16                 echo "$PIDFILE exists, process is already running or crashed"
17         else
18                 echo "Starting Redis server..."
19                 $EXEC $CONF
20         fi
21         ;;
22     stop)
23         if [ ! -f $PIDFILE ]
24         then
25                 echo "$PIDFILE does not exist, process is not running"
26         else
27                 PID=$(cat $PIDFILE)
28                 echo "Stopping ..."
29                 $CLIEXEC -a Abc123_ -p $REDISPORT shutdown
30                 while [ -x /proc/${PID} ]
31                 do
32                     echo "Waiting for Redis to shutdown ..."
33                     sleep 1
34                 done
35                 echo "Redis stopped"
36         fi
37         ;;
38     *)
39         echo "Please use start or stop as first argument"
40         ;;
41 esac

注意第29行,-a后面是你设置的redis密码

给脚本设置权限

[root@VM_6_102_centos src]# chmod 777 /etc/init.d/redis   

redis开启和关闭服务命令如下

[root@VM_6_102_centos src]# service redis start                   
Starting Redis server...
[root@VM_6_102_centos src]# service redis stop 
Stopping ...
Redis stopped
[root@VM_6_102_centos src]# 

3、开机自启

[root@VM_6_102_centos src]# chkconfig --add redis 

二、在java中应用

首先需要导入jar包,这里用的是jedis-2.1.0.jar

public static void main(String[] args) {
        Jedis jedis = new Jedis("your Redis Server IP", 6379);
        jedis.auth("Abc123_");
        //查看服务是否运行
        System.out.println("Server is running: "+jedis.ping());
        System.out.println(jedis.set("name", "zhangsan"));
        System.out.println(jedis.get("name"));
   }

 

posted @ 2017-03-30 17:04  阿龙阿  阅读(236)  评论(0编辑  收藏  举报