菜单开关

周梦康 发表于 2017-10-22 1215 次浏览 标签 : Java

免费领取阿里云优惠券 我的直播 - 《PHP 进阶之路》

服务端的继续使用 https://mengkang.net/1035.html#blog-title-4 里的代码
我们下面以 java 为例来说明跨语言的远程调用

完整的代码:
https://gitee.com/zhoumengkang/soa-01-java-client
https://gitee.com/zhoumengkang/soa-01-php-service

目录结构

.
└── net
    └── mengkang
        ├── Demo.java
        ├── rpc
        │   ├── RpcClient.java
        │   ├── RpcClientInvocationHandler.java
        │   └── RpcRequest.java
        └── sdk
            ├── User.java
            └── UserService.java

第三方给的 sdk

package net.mengkang.sdk;

public class User {
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                '}';
    }
}
package net.mengkang.sdk;

public interface UserService {
    User getUserInfo(Integer uid);
}

RPC 调用

package net.mengkang.rpc;

import java.lang.reflect.Proxy;

public class RpcClient {
    public final Object proxy(Class type) {
        RpcClientInvocationHandler handler = new RpcClientInvocationHandler(type);
        return Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, handler);
    }
}
package net.mengkang.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

class RpcClientInvocationHandler implements InvocationHandler{

    private Class service;

    public RpcClientInvocationHandler(Class clazz) {
        service = clazz;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class returnType = method.getReturnType();
        String[] serviceName =  service.getName().split("\\.");

        String url = "http://127.0.0.1:8081?service=" + serviceName[serviceName.length - 1] + "&action=" + method.getName();

        String httpResponse = RpcRequest.doPost(url, args);

        Object res = null;

        try{
            res = JSON.parseObject(httpResponse, returnType);
        }catch (JSONException e){
            e.printStackTrace();
        }

        return res;
    }
}
package net.mengkang.rpc;

import com.alibaba.fastjson.JSON;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class RpcRequest {
    public static String doPost(String url, Object content) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse httpResponse = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpPost.setConfig(requestConfig);
            String json = JSON.toJSONString(content);
            StringEntity entity = new StringEntity(json,"utf-8");
            httpPost.setEntity(entity);

            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                responseText = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return responseText;
    }
}

demo

package net.mengkang;

import net.mengkang.rpc.RpcClient;
import net.mengkang.sdk.User;
import net.mengkang.sdk.UserService;

public class Demo {
    public static void demo(){
        RpcClient rpcClient = new RpcClient();
        UserService userService = (UserService) rpcClient.proxy(UserService.class);
        User user = userService.getUserInfo(10);
        System.out.println(user.getId());
        System.out.println(user.toString());
    }

    public static void main(String args[]){
        Demo.demo();
    }
}

服务治理深入浅出(3)- 远程方法跨语言通信

嗨,老铁,欢迎来到我的博客!

如果觉得我的内容还不错的话,可以关注下我在 segmentfault.com 上的直播。我主要从事 PHP 和 Java 方面的开发,《深入 PHP 内核》作者之一。

[视频直播] PHP 进阶之路 - 亿级 pv 网站架构的技术细节与套路 直播中我将毫无保留的分享我这六年的全部工作经验和踩坑的故事,以及会穿插着一些面试中的 考点难点加分点

评论列表