使用 webservice 实现 RPC 调用
webservice 介绍
服务提供者
package com.zxw.service;
import javax.jws.WebService;
/**
* 创建需要发布的远程服务接口
* 使用@WebService发布的远程服务 默认情况下会将该接口的所有public的方法都发布,
* 如果不想发布可以在不想发布的方法上加@WebMethod()
*/
@WebService
public interface UserService {
public String SayHello(String name);
}
package com.zxw.service.impl;
import com.zxw.service.UserService;
import javax.jws.WebService;
@WebService
public class UserServiceImpl implements UserService {
public String SayHello(String name) {
return "hello "+name;
}
}
发布webservice服务
package com.zxw.app;
import com.zxw.service.UserService;
import com.zxw.service.impl.UserServiceImpl;
import javax.xml.ws.Endpoint;
/**
* 发布远程服务
*/
public class WsProviderApp {
public static void main(String[] args) {
//远程服务的访问url 发布的 webservice 服务的访问地址
String address="http://localhost:9999/ws";
//创建 UserService 对象
UserService userService=new UserServiceImpl();
//发布具体的 webservice 服务
Endpoint.publish(address,userService);
System.out.println("====webservice远程服务发布====");
}
}
运行生产者结果:
获取wdsl文档
服务消费者
wsimport生成消费者代码
在jdk安装包里
使用cmd打开dos窗口
-d 代码存储位置 ,-p 包的位置
自动生成后
消费远程服务
package com.zxw.app;
import com.zxw.client.UserServiceImpl;
import com.zxw.client.UserServiceImplService;
public class WsConsumerApp {
public static void main(String[] args) {
//创建服务类对象
UserServiceImplService service=new UserServiceImplService();
//获得远程服务的代理对象
UserServiceImpl userService = service.getUserServiceImplPort();
System.out.println(userService.getClass().getName());
//进行远程服务调用 通过远程服务的代理对象
String result = userService.sayHello("Jess");
System.out.println("result="+result);
}
}
运行消费者结果: