Redis在javaWeb项目中的应用

1,自己搭建服务器,安装redis,网上很多单独安装方法,不说了

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


   redis.clients
   jedis
   2.9.0

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

Redis在javaWeb项目中的应用_第1张图片

 

你可能感兴趣的:(redis)