SpringBoot整合使用Redis
    		       		warning:
    		            这篇文章距离上次修改已过426天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中整合Redis,你可以使用spring-boot-starter-data-redis依赖。以下是整合的步骤和示例代码:
- 添加依赖到你的
pom.xml文件中: 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>- 在
application.properties或application.yml中配置Redis连接信息: 
# application.properties
spring.redis.host=localhost
spring.redis.port=6379或者使用YAML格式:
# application.yml
spring:
  redis:
    host: localhost
    port: 6379- 使用
RedisTemplate或StringRedisTemplate操作Redis: 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
 
@RestController
public class RedisController {
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    @GetMapping("/set/{key}/{value}")
    public String set(@PathVariable String key, @PathVariable Object value) {
        redisTemplate.opsForValue().set(key, value);
        return "success";
    }
 
    @GetMapping("/get/{key}")
    public Object get(@PathVariable String key) {
        return redisTemplate.opsForValue().get(key);
    }
}这个例子中,我们创建了一个简单的RESTful控制器,提供了两个接口,一个用于设置键值对到Redis,另一个用于从Redis中获取键对应的值。
确保你的Spring Boot应用已经配置了Redis相关的属性,并且Redis服务器正在运行,你就可以通过HTTP请求来操作Redis了。
评论已关闭