sprinboot集成redis
1. 添加依赖
首先,在pom.xml 文件中添加 Spring Boot 的 Redis 起步依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置 Redis
在 application.properties 或 application.yml 文件中配置 Redis 服务器的连接信息。
spring.redis.host=localhost
spring.redis.port=6379
3. 使用 Redis
一旦添加了依赖并配置了 Redis,你就可以在你的应用程序中使用 Redis 了。Spring Boot 提供了 RedisTemplate 和 StringRedisTemplate,用于简化 Redis 数据访问。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisExample {
private final RedisTemplate<String, Object> redisTemplate;
@Autowired
public RedisExample(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void setValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
}
4. 高级配置
如果你需要进行更高级的配置,比如使用密码保护 Redis 服务器,或者配置连接池,你可以在你的 application.properties 或 application.yml 文件中添加更多的配置选项。
# 使用密码
spring.redis.password=yourpassword
# 配置连接池
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0