Spring Boot 单机 Redis 配置教程
要在 Spring Boot 中配置单机 Redis,你需要执行以下步骤:
- 添加 Redis 依赖:在 'pom.xml' 文件中添加以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置 Redis 连接信息:在 'application.properties' 文件中添加以下配置信息:
spring.redis.host=localhost
spring.redis.port=6379
这里假设 Redis 服务器运行在本地主机上,端口号为默认的 6379。
- 创建 Redis 配置类:创建一个 Java 类,例如 'RedisConfig',并添加以下内容:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
}
这个配置类用于创建一个 'RedisTemplate' 实例,以便在应用程序中使用 Redis。
- 使用 RedisTemplate:在需要使用 Redis 的地方,如服务类或控制器中,注入 'RedisTemplate' 实例,并使用它执行 Redis 操作。例如:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setValue(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String getValue(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
}
现在你可以通过调用 'setValue' 和 'getValue' 方法来设置和获取 Redis 中的键值对。
这样,你就完成了在 Spring Boot 中配置单机 Redis 的过程。记得在使用完 Redis 之后关闭连接,以释放资源。
原文地址: https://www.cveoy.top/t/topic/qFFO 著作权归作者所有。请勿转载和采集!