使用Jedis和SpringBoot连接远程Linux服务器上的Redis缓存数据库(以云服务器为实例)

redis 可以远程连接 redis连接远程服务器_redis

一、Jedis连接

1.导入Jedis相关依赖

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

2. 连接远程Redis缓存数据库

1.明确远程服务器的公网IP(Xshell查看方式)

redis 可以远程连接 redis连接远程服务器_linux_02


主机栏显示的是当前服务器的公网IP。

2.修改redis.conf配置

redis 可以远程连接 redis连接远程服务器_Redis_03

  1. 将保护模式(protected-mode)由yes修改成no。
  2. 将端口号6379开放(阿里云需要去云服务器管理控制台中的安全组设置6379端口)。
  3. 在Linux服务器的防火墙放开6379/tcp。
  4. 将bind 127.0.0.1注释。

redis 可以远程连接 redis连接远程服务器_Redis_04

3.在远程服务器上启动Redis服务。

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是否已经有密码

redis 可以远程连接 redis连接远程服务器_Redis_05


2. config set requirepass 你的密码 设置redis密码

redis 可以远程连接 redis连接远程服务器_linux_06


3.在redis客户端试试密码是否设置成功

直接执行任何操作 如果没有验证密码 则无法操作

redis 可以远程连接 redis连接远程服务器_springboot_07


使用 auth 你的密码 命令来验证redis密码,下图为验证成功。

redis 可以远程连接 redis连接远程服务器_linux_08

5.使用Jedis连接

redis 可以远程连接 redis连接远程服务器_redis_09


执行上述代码 返回值为PONG 表示连接成功!

redis 可以远程连接 redis连接远程服务器_linux_10

二、使用SpringBoot整合远程Redis

1.导入相关依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </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。