json-rpc以前并没有接触过,json相对来说又有传输占用带宽较小等广为人知的优点,便以此篇为个契机学习一下. jsonrpc4j是briandilley开发,项目的地址是github jsonrpc4j 服从json-rpc的规范,规范链接在此 其主要支持下面这4类客户端: Streaming server (InputStream \ OutputStream) HTTP Server (HttpServletRequest \ HttpServletResponse) Portlet Server (ResourceRequest \ ResourceResponse) Socket Server (StreamServer) 这次主要使用的是HTTP Server
package com.littleji.jsonrpc.demo; import java.io.Serializable; public class DemoBean implements Serializable{ private static final long serialVersionUID = -5141784935371524L; private int code; private String msg; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
Service和其Implement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package com.littleji.jsonrpc.demo; /** * Created by Jimmy on 2016/12/6. */ public interface DemoService { public DemoBean getDemo(String code, String msg); public Integer getInt(Integer code); public String getString(String msg); public void doSomething(); }
JsonRpcHttpClient client = new JsonRpcHttpClient( new URL("http://example.com/UserService.json")); User user = client.invoke("createUser", new Object[] { "bob", "the builder" }, User.class);
或者使用ProxyUtil类结合接口,来创建一个动态的代理,如下所示:
1 2 3 4 5 6 7 8 9
JsonRpcHttpClient client = new JsonRpcHttpClient( new URL("http://example.com/UserService.json")); UserService userService = ProxyUtil.createClientProxy( getClass().getClassLoader(), UserService.class, client); User user = userService.createUser("bob", "the builder");