在Java中实现SingleFlight模式,可以通过使用ConcurrentHashMap
和CompletableFuture
来管理并发请求。以下是一个示例代码,展示了如何在Java中实现SingleFlight模式:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class SingleFlight<T> {
private final ConcurrentHashMap<String, CompletableFuture<T>> flightMap = new ConcurrentHashMap<>();
public CompletableFuture<T> doRequest(String key, RequestFunction<T> requestFunction) {
CompletableFuture<T> future = flightMap.computeIfAbsent(key, k -> {
CompletableFuture<T> newFuture = new CompletableFuture<>();
requestFunction.apply().whenComplete((result, throwable) -> {
if (throwable != null) {
newFuture.completeExceptionally(throwable);
} else {
newFuture.complete(result);
}
flightMap.remove(k);
});
return newFuture;
});
return future;
}
@FunctionalInterface
public interface RequestFunction<T> {
CompletableFuture<T> apply();
}
public static void main(String[] args) {
SingleFlight<String> singleFlight = new SingleFlight<>();
for (int i = 0; i < 10; i++) {
int finalI = i;
CompletableFuture<String> future = singleFlight.doRequest("key", () -> {
return CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
return "result from request " + finalI;
});
});
future.whenComplete((result, throwable) -> {
if (throwable != null) {
System.out.println("Error: " + throwable.getMessage());
} else {
System.out.println("Request " + finalI + " got result: " + result);
}
});
}
try {
TimeUnit.SECONDS.sleep(5); // 等待所有请求完成
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
SingleFlight
类:管理并发请求的核心类。
flightMap
:使用 ConcurrentHashMap
来存储正在进行的请求。doRequest
方法:接收一个键和一个请求函数。如果相同键的请求已经在进行中,则返回相同的 CompletableFuture
;否则,执行新的请求函数,并在请求完成后移除键。RequestFunction
接口:定义了一个函数接口,用于表示异步请求函数。
main
方法:模拟了10个并发请求,所有请求都使用相同的键 "key"
。由于使用了SingleFlight模式,这些请求会被合并为一个请求,结果会被共享。
运行上述代码,你会看到所有请求共享同一个结果:
Request 0 got result: result from request 0
Request 1 got result: result from request 0
Request 2 got result: result from request 0
Request 3 got result: result from request 0
Request 4 got result: result from request 0
Request 5 got result: result from request 0
Request 6 got result: result from request 0
Request 7 got result: result from request 0
Request 8 got result: result from request 0
Request 9 got result: result from request 0
通过使用 ConcurrentHashMap
和 CompletableFuture
,我们可以在Java中实现SingleFlight模式,有效地减少对同一资源的重复请求,提高系统性能。
package org.example.Serialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonSerialize(using = StudentSerializer.class)
@JsonDeserialize(using = StudentDeserializer.class)
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
}
package org.example.Serialize;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class StudentSerializer extends JsonSerializer<Student> {
@Override
public void serialize(Student student, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField(student.getClass().getSimpleName(), "学生姓名=" + student.getName() + ",年龄=" + student.getAge());
jsonGenerator.writeEndObject();
}
}
package org.example.Serialize;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.lang.reflect.Constructor;
public class StudentDeserializer extends JsonDeserializer<Student> {
@Override
public Student deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
String text = node.get(Student.class.getSimpleName()).asText();
System.out.println("反序列化中:" + text + " " + Student.class.getSimpleName());
String[] elements = text.split(",");
Student student = new Student();
for (String element : elements) {
String[] keyVal = element.split("=");
if (keyVal[0].equals("学生姓名")) {
student.setName(keyVal[1]);
}
if (keyVal[0].equals("年龄")) {
student.setAge(Integer.parseInt(keyVal[1]));
}
}
return student;
}
}
package org.example.Serialize;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SerializeTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Student student = new Student("hi", 20);
String stuStr = objectMapper.writeValueAsString(student);
System.out.println(stuStr);
Student stuRes = objectMapper.readValue(stuStr, Student.class);
System.out.println(stuRes);
}
}
运行结果:
{"Student":"学生姓名=hi,年龄=20"}
反序列化中:学生姓名=hi,年龄=20 Student
Student(name=hi, age=20)
Process finished with exit code 0