Spring Boot 的 JSON RPC(客户端示例) - briandilley/jsonrpc4j Wiki

Spring Boot 和 JSON-RPC for Java 快速入门

客户

配置

为了让客户端在 @Configuration 类中工作,您需要定义 JsonRpcHttpClient bean。之后,您可以为正在使用的服务创建代理(请注意,端点假定您在端口 8080 上运行 JSON-RPC for Java Server 示例):

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);
    }
}

服务

现在我们需要定义我们在上一步中已经注入 bean 的代理。为此,请创建一个模仿您正在使用的服务的界面。在我们的例子中,它是我们在前面的示例中设置的服务器端!

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);
}

要调用我们的服务,我们需要做的就是将客户端自动连接到服务并调用它的方法

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);
    }
}

这个例子的完整源代码可以在这里找到

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值