面向服务架构(SOA)是目前软件架构发展的趋势,它伴随云计算(Cloud computing)而产生。
SOA八大设计原则:
1.标准化服务合约()
2.服务松散耦合
3.服务抽象
4.服务可复用性
5.服务自治
6.服务无状态性
7.服务可发现性
8.服务可组合性
实验
使用命令行工具生成代码
1.使用jdk自带的wsimport
2.下载Apache CXF工具(或通过maven插件使用)的wsdl2java
图 wsimport报错
原因是所调用的jaxb不支持ref属性。
我们需要修改一下wsdl文件
将其中所有的
1 | <s:element ref="s:schema" /> |
修改为
1 | <s:any minOccurs="2" maxOccurs="2"/> |
再次运行可以了
图 再次运行wsimport成功
接下来编写客户端代码:
1 | package example; |
调用成功:
图 运行main函数成功
使用IDEA新建WebService项目
图 IDEA新建Web Service项目
生成的项目目录即初始代码如下(web.xml是刚才勾选web所自动生成的):
图 初始代码
接着,IDEA使用wsimport工具根据远程wsdl文档生成访问远程接口的客户端代码:
图 IDEA操作
输入远程接口的wsdl文档地址:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl
接下来,我们看看系统默认生成的HelloWorld类,我们在main函数最后添加一行启动成功的log
1 | System.out.println("WebService starting success... address:" + address); |
然后启动 HelloWorld 服务,打开对应网址:
图 启动HelloWorld服务
我们继续打开wsdl文档,其他人可以使用该文档生成他们的客户端代码,就想刚才我们调用weather服务一样。
图 HelloWorld的WSDL文档
由此,我们知道,由WebService服务接口代码可以转换为wsdl文档,由WSDL文档可以生成调用的客户库代码。
比较下OpenAPI的文档和WSDL的文档:
1 | {"swagger":"2.0","info":{"description":"天气查询","version":"0.1","title":"接口文档","contact":{"name":"Shane","url":"localhost:8025","email":"Email"}},"host":"localhost:8025","basePath":"/","tags":[{"name":"天气查询接口","description":"Weather Forecast Controller"}],"paths":{"/v1/weather/forecast":{"get":{"tags":["天气查询接口"],"summary":"天气查询","operationId":"queryWeatherUsingGET","produces":["*/*"],"parameters":[{"name":"location","in":"query","description":"location","required":false,"type":"string"},{"name":"time","in":"query","description":"time","required":false,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"object"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/v1/weather/offline":{"get":{"tags":["天气查询接口"],"summary":"主动下线","operationId":"offLineUsingGET","produces":["*/*"],"responses":{"200":{"description":"OK"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/v1/weather/reonline":{"get":{"tags":["天气查询接口"],"summary":"重新上线","operationId":"reOnlineUsingGET","produces":["*/*"],"responses":{"200":{"description":"OK"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}}}} |
评论
shortname
for Disqus. Please set it in_config.yml
.