今天在做Springboot整合Redis中碰到下列错误:
基于以上的错误首先在Xshell或者其他远程操控虚拟机的软件上看能不能连接到Redis:
[zzl@localhost ~]$ redis-cli -h 192.168.136.132 -p 6379 -a ******
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
192.168.136.132:6379> get name
"joker"
192.168.136.132:6379>
如果在Xshell可以连接并且可以操作Redis ,则原因肯定出现在springboot中,首先来排查一下配置文件:以下是我的依赖以及配置文件
pom.xml:
<!--redis依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--common-pool--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency>
application.properties:
spring.redis.host = 192.168.136.132
spring.redis.port = 6379
spring.redis.password = ****
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=100ms
然后就是运行代码:
package com.example.redisdatademo;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;import javax.annotation.Resource;@SpringBootTest
class RedisDataDemoApplicationTests {//依赖注入@Resourceprivate RedisTemplate redisTemplate;//注释:redisTemplate返回的是一个Object对象@Testvoid contextLoads() {//写入数据redisTemplate.opsForValue().set("name","TestData");//获取数据Object object = redisTemplate.opsForValue().get("name");System.out.println(object);}}
成功输出:
查看更多Redis相关知识:https://blog.csdn.net/qq_62366797/article/details/136802293