JSON-RPC
offical
JSON-RPC 2.0 specification
jsonrpc4j
article
Spring Boot
Server
Configuration.
@Configuration
public class JsonRpcConfig {
@Bean
public AutoJsonRpcServiceImplExporter autoJsonRpcServiceImplExporter() {
AutoJsonRpcServiceImplExporter exporter = new AutoJsonRpcServiceImplExporter();
exporter.setRegisterTraceInterceptor(true);
MultipleInvocationListener invocationListener = new MultipleInvocationListener();
exporter.setInvocationListener(invocationListener);
exporter.setShouldLogInvocationErrors(false);
//替换默认的json序列化
exporter.setObjectMapper(ModelObject.OBJECT_MAPPER);
//自定义错误处理器,便于记录log
exporter.setErrorResolver(new CustomErrorResolver());
return exporter;
}
}
service interface.
@JsonRpcService("/calculator")
public interface ExampleServerAPI {
int multiplier(@JsonRpcParam(value = "a") int a, @JsonRpcParam(value = "b") int b);
}
serivce implement.
@Service
@AutoJsonRpcServiceImpl
public class ExampleServerAPIImpl implements ExampleServerAPI {
@Override
public int multiplier(int a, int b) {
return a * b;
}
}
request.
curl -H "Content-Type:application/json" -d '{"id":"1","jsonrpc":"2.0","method":"multiplier","params":{"a":5,"b":6}}' http://localhost:8080/calculator
$.ajax({
data: JSON.stringify({"jsonrpc": "2.0", "method": "multiplier", "params": params, "id": 1234}),
url: '/calculator',
type: "post",
dataType: "json",
contentType: "application/json",
success: function (data) {
//结果处理
}
Client
Configuration.
@Configuration
public class ApplicationConfig {
private static final String endpoint = "http://localhost:8080/calculator";
@Bean
public JsonRpcHttpClient jsonRpcHttpClient() {
URL url = null;
//You can add authentication headers etc to this map
Map<String, String> map = new HashMap<>();
try {
url = new URL(ApplicationConfig.endpoint);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new JsonRpcHttpClient(url, map);
}
@Bean
public ExampleClientAPI exampleClientAPI(JsonRpcHttpClient jsonRpcHttpClient) {
return ProxyUtil.createClientProxy(getClass().getClassLoader(), ExampleClientAPI.class, jsonRpcHttpClient);
}
}
service proxy.
public interface ExampleClientAPI {
int multiplier(@JsonRpcParam(value = "a") int a, @JsonRpcParam(value = "b") int b);
}
service invoke.
@Service
public class ExampleService {
@Autowired
private ExampleClientAPI exampleClientAPI;
public int multiply(int a, int b) {
return exampleClientAPI.multiplier(a, b);
}
}
use validator
在service interface类使用@Validated
注解,在方法的参数上使用validation aonnation即可生效,参数为对象时加@Valid
注解。
@Validated
@JsonRpcService("/api/jsonrpc/userService")
public interface UserService {
PageList<UserVO> queryUsers(@NotNull @Valid UserQueryVO query);
UserVO getUser(@NotNull @Positive Long id);
Long addUser(@NotEmpty @Pattern(regexp ="^{0-9a-zA-Z_]{1,20}$") String username, @NotEmpty @Pattern(regexp ="^{0-9a-zA-Z_]{1,20}$") String password);
}