<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
<version>version>
dependency>
2. 连接远程Redis缓存数据库
1.明确远程服务器的公网IP(Xshell查看方式)
主机栏显示的是当前服务器的公网IP。
- 将保护模式(protected-mode)由yes修改成no。
- 将端口号6379开放(阿里云需要去云服务器管理控制台中的安全组设置6379端口)。
- 在Linux服务器的防火墙放开6379/tcp。
- 将bind 127.0.0.1注释。
cd /usr/bin
redis-server myconf/redis.conf # 启动redis服务端
ps -aux|grep redis # 查看redis相关进程是否开启
redis-cli -p 6379 # 启动redis客户端
4.设置Redis的密码
1.config get requirepass 查询redis是否已经有密码
2. config set requirepass 你的密码 设置redis密码
3.在redis客户端试试密码是否设置成功
直接执行任何 *** 作 如果没有验证密码 则无法 *** 作
使用 auth 你的密码 命令来验证redis密码,下图为验证成功。
执行上述代码 返回值为PONG 表示连接成功!
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
目前SpringBoot版本为2.6.7,它支持lettuce作为其连接Redis的客户端,lettuce的底层采用了netty网络框架,并发性和网络传输性能更佳,也时SpringBoot官方推荐使用的包(还有Redisson)。
2.配置application.yml / application.properties# 配置 Redis
spring:
redis:
host: 你的远程Redis服务器的公网IP地址
port: 6379
password: 你的Redis密码
3.测试连接
在SpringBoot的中, *** 作Redis需要使用RedisTemplate对象,首先需要从Spring容器中注入该对象。
@Autowired
private RedisTemplate redisTemplate;
向远程redis中插入一个string类型的对象
@SpringBootTest
class Redis02SpringbootApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
// redisTemplate
// opsForValue *** 作字符串 类似String
// opsForList *** 作List 类似List
// opsForSet
// opsForHash
// opsForZset
// opsForGeo
// opsForHyperLoglog
// 获取连接
//RedisConnection connection = Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection();
redisTemplate.opsForValue().set("mykey1", "123");
System.out.println(redisTemplate.opsForValue().get("mykey1"));
}
}
成功后可以在远程Redis数据库中看到mykey1。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)