-
Notifications
You must be signed in to change notification settings - Fork 440
JSON RPC for Java Client & Spring Boot (Client example)
Markus Karileet edited this page Jul 15, 2016
·
1 revision
In order to get a client working in the @Configuration class you'll need to define the JsonRpcHttpClient bean. After that you can create your proxy for the service being consumed (notice that the endpoint assumes that you are running the JSON-RPC for Java Server example on port 8080):
package example.jsonrpc4j.springboot;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import com.googlecode.jsonrpc4j.ProxyUtil;
import example.jsonrpc4j.springboot.api.ExampleClientAPI;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
@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);
}
}
Now we need to define out proxy that we already injected in a bean in the previous step. For this, create an interface mimicking the service you're consuming. In our case, it's the server side that we set up in the previous example!
package example.jsonrpc4j.springboot.api;
import com.googlecode.jsonrpc4j.JsonRpcParam;
public interface ExampleClientAPI {
int multiplier(@JsonRpcParam(value = "a") int a, @JsonRpcParam(value = "b") int b);
}
To call our service, all we need to do is autowire the client to a service and call it's methods
package example.jsonrpc4j.springboot.service;
import example.jsonrpc4j.springboot.api.ExampleClientAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
@Autowired
private ExampleClientAPI exampleClientAPI;
public int multiply(int a, int b) {
return exampleClientAPI.multiplier(a, b);
}
}
The whole source code for this example can be found here