【SpringBoot】| SpringBoot 集成 Redis
在Spring Boot中集成Redis,你需要做以下几个步骤:
- 添加依赖到你的
pom.xml
或build.gradle
文件中。
使用Maven时,在pom.xml
中添加:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
使用Gradle时,在build.gradle
中添加:
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
- 配置
application.properties
或application.yml
文件。
在application.properties
中添加:
spring.redis.host=localhost
spring.redis.port=6379
或者在application.yml
中添加:
spring:
redis:
host: localhost
port: 6379
- 使用
RedisTemplate
或StringRedisTemplate
操作Redis。
例如,在一个Service中使用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setKeyValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getValueByKey(String key) {
return redisTemplate.opsForValue().get(key);
}
}
这样,你就可以在你的Spring Boot应用中使用Redis来存储和检索数据了。
评论已关闭