以下是使用Spring Boot与Redis集群进行交互的代码示例:
1. 添加Redis依赖:
- 在`pom.xml`文件中添加Spring Data Redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置Redis集群:
- 在`application.properties`或`application.yml`文件中配置Redis集群的连接信息,例如:
spring.redis.cluster.nodes=host1:port1,host2:port2,host3:port3
3. 使用RedisTemplate进行操作:
- 创建一个Redis的操作类,例如`RedisService`,并注入`RedisTemplate`对象:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
private final RedisTemplate<String, String> redisTemplate;
@Autowired
public RedisService(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void setValue(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
}
4. 使用RedisService进行操作:
- 在需要使用Redis的地方,注入`RedisService`对象并调用相应的方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/redis")
public class RedisController {
private final RedisService redisService;
@Autowired
public RedisController(RedisService redisService) {
this.redisService = redisService;
}
@GetMapping("/{key}")
public String getValue(@PathVariable String key) {
return redisService.getValue(key);
}
}
在上述示例中,我们通过注入`RedisTemplate`对象来操作Redis集群。在`RedisService`中,我们定义了一些常用的操作方法,例如`setValue()`和`getValue()`,用于设置和获取Redis的键值对。
在`RedisController`中,我们使用`RedisService`来处理相关的请求,例如通过`/redis/{key}`路径获取Redis中的值。
确保你的Redis集群已正确配置,并替换示例代码中的相应信息,如Redis集群节点的主机和端口等。