Contents

Spring boot redis 使用踩坑

Contents

连接失败

windows下开发spring boot项目,需要使用redis服务代替session工作,所以直接使用homestead的虚拟机来提供数据库、redis服务等,免去自己配置各种服务的麻烦,redis服务本来使用laravel连接的时候一切正常,但是换到使用spring-boot-redis连接就提示连接被主机中的其他软件关闭,然后一直在reconnect,错误如下:

2018-08-30 15:35:05.969 ERROR 8892 --- [0.0.1-80-exec-1] m.i.o.C.Common.CommonController          : org.springframework.data.redis.RedisSystemException: Redis exception; nested exception is io.lettuce.core.RedisException: java.io.IOException: 您的主机中的软件中止了一个已建立的连接。
2018-08-30 15:35:06.038  INFO 8892 --- [ioEventLoop-4-3] i.l.core.protocol.ReconnectionHandler    : Reconnected to 127.0.0.1:60030
2018-08-30 15:35:06.138  INFO 8892 --- [ioEventLoop-4-4] i.l.core.protocol.ReconnectionHandler    : Reconnected to 127.0.0.1:60030
2018-08-30 15:35:06.241  INFO 8892 --- [ioEventLoop-4-1] i.l.core.protocol.ReconnectionHandler    : Reconnected to 127.0.0.1:60030
2018-08-30 15:35:06.338  INFO 8892 --- [ioEventLoop-4-2] i.l.core.protocol.ReconnectionHandler    : Reconnected to 127.0.0.1:60030
2018-08-30 15:35:06.439  INFO 8892 --- [ioEventLoop-4-3] i.l.core.protocol.ReconnectionHandler    : Reconnected to 127.0.0.1:60030

通过搜索发现,是redis监听的地址配置问题,打开redis配置文件:

sudo vim /etc/redis/redis.conf

bind 127.0.0.1 ::1修改为bind 0.0.0.0 ::1

重新启动redis:

sudo service redis restart

/x00

使用一下方法添加缓存后,value前面会出现一堆/x00

redis.opsForValue().set("param", "jsonParam", 100L);

如下图:

/redis-cli-x00.png
x00

进过查阅源码发现,set方法有多个重载形式,只有三个参数时,第三个参数表示偏移量,所以前面出现了很多的\x00,如果想设置过期时间,需要传入四个参数,第三个参数表示时间量,第四个参数表示第三个参数的单位。如下:

redis.opsForValue().set("param", "jsonParam", 100LTimeUnit.SECONDS);