要想通过 Java 操作 redis,首先要连接上 redis 服务器,推荐看通过 Java 操作 redis -- 连接 redis
创建项⽬
勾选 NoSQL 中的 Spring Data Redis
当然, 把 Web 中的 Spring Web 也勾选⼀下.⽅便写接进⾏后续测试.
配置 redis 服务地址
在 application.properties 配置文件中配置参数:
#redis 服务器的地址
spring.redis.host=127.0.0.1
#redis 服务器的端口号
spring.redis.port=8888
至于为什么是这里配置的 redis 端口是本地的 8888 端口,相信看了本文章头部推荐的博客以后就很清楚了,我们用 shh 的端口转发,将服务器上 redis 的 6379 端口映射到了本地的 8888 端口
测试代码
package com.example.redisspringdemo.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;