springboot项目集成redis后怎么使用redis实现一个栈,实现对一个值班表中的人轮询
时间: 2024-05-08 14:15:11 浏览: 188
1. 首先需要在pom.xml中添加redis和jedis的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
```
2. 在application.properties中配置redis连接信息:
```properties
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
# spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=10000
```
3. 编写一个RedisStack类,用于实现栈的基本操作:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class RedisStack<T> {
private static final String KEY_PREFIX = "redis_stack:";
private final RedisTemplate<String, T> redisTemplate;
@Autowired
public RedisStack(RedisTemplate<String, T> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void push(String key, T value) {
redisTemplate.opsForList().leftPush(KEY_PREFIX + key, value);
}
public T pop(String key) {
return redisTemplate.opsForList().leftPop(KEY_PREFIX + key);
}
public List<T> getAll(String key) {
return redisTemplate.opsForList().range(KEY_PREFIX + key, 0, -1);
}
}
```
4. 编写一个DutySchedule类,用于实现值班表的轮询:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class DutySchedule {
private final RedisStack<String> redisStack;
@Autowired
public DutySchedule(RedisStack<String> redisStack) {
this.redisStack = redisStack;
}
public String getNextDuty(String key) {
List<String> allDuties = redisStack.getAll(key);
if (allDuties == null || allDuties.isEmpty()) {
return null;
}
String lastDuty = redisStack.pop(key);
redisStack.push(key, lastDuty);
return lastDuty;
}
}
```
5. 在其他代码中使用RedisStack和DutySchedule:
```java
@Autowired
private RedisStack<String> redisStack;
@Autowired
private DutySchedule dutySchedule;
@Test
public void testRedisStack() {
redisStack.push("mykey", "value1");
redisStack.push("mykey", "value2");
redisStack.push("mykey", "value3");
List<String> allValues = redisStack.getAll("mykey");
System.out.println(allValues);
String popValue = redisStack.pop("mykey");
System.out.println(popValue);
allValues = redisStack.getAll("mykey");
System.out.println(allValues);
}
@Test
public void testDutySchedule() {
redisStack.push("duty_schedule", "张三");
redisStack.push("duty_schedule", "李四");
redisStack.push("duty_schedule", "王五");
System.out.println(dutySchedule.getNextDuty("duty_schedule"));
System.out.println(dutySchedule.getNextDuty("duty_schedule"));
System.out.println(dutySchedule.getNextDuty("duty_schedule"));
System.out.println(dutySchedule.getNextDuty("duty_schedule"));
}
```
阅读全文