webservice
根据自己的经验,总结webservice的使用方法
webservice接口主要分为两个部分
- 服务端
- 客户端
在实际编写代码的过程中,基于springboot的服务端与客户端的代码总结如下(不提供具体的代码实现):
一、服务端
1、相关依赖
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.0.1</version>
</dependency>
2、service层
service层主要分为接口和接口的实现类,在接口上添加注解@WebService,在实现类上添加注解@Service。在网上查找的过程中,发现大部分好像都是实现类上添加注解@WebService,当然我使用的也是可以用的。
在实现类中编写代码实现读取数据库数据,我在实际编写过程中使用了缓存来存储数据,注解语句为:
//value为缓存的名称,在 spring 配置文件中定义,必须指定至少一个
//key为缓存的key,例如当key为id时,首先在缓存中查找id值所对应的数据
@Cacheable(value = "" , key = "#id")
注解使用在方法上。使用该注解,需在启动类添加相应注解
@EnableCaching
3、发布
在项目中创建了cxf包,并创建名为JaxWsConfig的java文件
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import javax.xml.ws.Endpoint;
@Configuration
public class JaxWsConfig {
@Resource
private Bus bus;
@Resource
private ServiceImpl Service;
public ServletRegistrationBean disServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new CXFServlet(), "/ServiceImpl/*");
return servletRegistrationBean;
}
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
/** JAX-WS
* 站点服务
* **/
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(bus, Service);
endpoint.publish("/Service");
return endpoint;
}
}
这段代码是我从网上查找的能发布服务端的全部代码,亲测好用。
运行项目后,可测试连接:
http://localhost:8080/ServiceImpl/Service?wsdl
如果出现内容为xml文件内容,则表示发布成功。
二、客户端
1、导入webservice接口
客户端能调用webservice接口,我使用的方法是wsmiport命令。
在cmd命令行中运行如下命令:
wsimport -s 客户端项目路径\项目名\src\main\java -p 包名 -keep http://localhost:8080/ServiceImpl/Service?wsdl
其中因为wsimport命令使用的是项目使用的jdk安装包的bin文件夹下的wsimport.exe,所以使用时需要带上全路径名。例如我的jdk安装在D盘的jdk8的文件夹下,所以wsmiport命令为:D:\jdk8\bin\wsimport
-p: 包名是导入webservice后,文件的保存位置,一般位于项目的src\main\java下,直接写com.xxx.xxx
-keep: 发布的webservice链接
运行以上命令后,会在项目中生成相应文件,接下来就可以使用服务端的接口了。
2、调用webservice接口
在service层的实现类的方法中添加如下代码:
ServiceImplService ws = new ServiceImplService();
com.ntdq.hd_siqu.Service wp = ws.getServiceImplPort();
其中ServiceImplService是根据服务端的webservice接口生成的Java文件中,实现类的文件。然后直接调用wp的方法就可以了(调用的wp的方法就是服务端接口实现类的方法)。我是用的软件是IDEA,会自动提示wp包含的方法。
总结
以上所有内容是我通过在B站上看的一些教学视频和网上搜索,结合自己的实践经验总结出来的,其中可能存在一些错误,表达上也有所欠缺,但还是希望能对看到这篇博客的人有所帮助。