Redis在javaWeb項目中的應用

1,自己搭建服務器,安裝redis,網上很多單獨安裝方法,不說了

2,在javaweb工程中引入依賴,jedis是操作redis的客戶端

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

3,程序中用jedis對象就可以操作redis服務器了。

Jedis jedis = new Jedis("192.168.150.128",6379);

System.out.println(jedis.ping());
jedis.set("name", "lucky");
System.out.println(jedis.get("name"));
jedis.close();

4,這裏說明一下,我的虛擬機centOS7在啓動redis的出現的問題。

java項目一直啓動報錯,連接超時,這個看這個文檔,很詳細:https://www.cnblogs.com/changqijing/p/8489732.html

然而,我在本地windows cmd下可以telnet訪問虛擬機的6379端口。

這裏先改了配置文件redis.conf的連接超時的設置(原來是0,後來改成5000)

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 5000

然後啓動java服務,發現這次報錯是

DENIED Redis is running in 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. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

這次更改配置文件 (原來是yes 現在改成no)

# By default protected mode is enabled. You should disable it only if
# you are sure you want clients from other hosts to connect to Redis
# even if no authentication is configured, nor a specific set of interfaces
# are explicitly listed using the "bind" directive.
protected-mode no

這次可以連接上了,但是啓動的時候和普通的啓動不一樣,沒有出現redis那個畫面,啓動是這樣的。

這塊需要注意,需要先kill掉原來的redis進程,再啓動,且啓動時候需要加載配置文件啓動,配置文件需要從根目錄開始寫路徑。

[root@localhost src]# ./redis-server /usr/redis/redis-3.2.11/redis.conf &
[1] 18854
[root@localhost src]# netstat -ntlp|grep 6379
tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN      18855/./redis-serve

這是更改配置文件 (原來是yes,現在改爲no)不守護進程

# By default Redis does not run as a daemon. Use 'yes' if you need it.
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
daemonize no

這樣再次啓動服務器的redis

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章