0


SpringBoot整合WebService

SpringBoot整合WebService

WebService是一个比较旧的远程调用通信框架,现在企业项目中用的比较少,因为它逐步被SpringCloud所取代,它的优势就是能够跨语言平台通信,所以还有点价值,下面来看看如何在SpringBoot项目中使用WebService

我们模拟从WebService客户端发送请求给WebService服务端暴露的下载文件服务,并获取服务端返回的文件保存到本地

环境

SpringBoot2.7.3

Jdk17

服务端

在SpringBoot中整合WebService的服务端,需要通过一个配置文件将服务接口暴露出去给客户端调用

项目结构

image-20230727183518916

配置

服务端POM

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.3</version><relativePath/><!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>webservice</artifactId><version>0.0.1-SNAPSHOT</version><name>webservice</name><description>webservice</description><properties><java.version>17</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--cxf--><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-transports-http</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-frontend-jaxws</artifactId><version>3.5.1</version></dependency><!--hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.12</version></dependency><!--fastjson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.16</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

服务端YML

server:# 必须配置端口,客户端需要port:7001

FileCxfConfig

该文件为WebService服务暴露配置文件

packagecom.example.webservice.config;importcom.example.webservice.service.FileCxfService;importcom.example.webservice.service.impl.FileCxfServiceImpl;importorg.apache.cxf.Bus;importorg.apache.cxf.bus.spring.SpringBus;importorg.apache.cxf.jaxws.EndpointImpl;importorg.apache.cxf.transport.servlet.CXFServlet;importorg.springframework.boot.web.servlet.ServletRegistrationBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjavax.xml.ws.Endpoint;@ConfigurationpublicclassFileCxfConfig{@Bean(name =Bus.DEFAULT_BUS_ID)publicSpringBusspringBus(){returnnewSpringBus();}@Bean(name ="downloadFileBean")publicServletRegistrationBeandispatcherServlet(){ServletRegistrationBean wbsServlet =newServletRegistrationBean(newCXFServlet(),"/file/*");return wbsServlet;}@BeanpublicFileCxfServicefileCxfService(){returnnewFileCxfServiceImpl();}@BeanpublicEndpointendpointPurchase(SpringBus springBus,FileCxfService fileCxfService){EndpointImpl endpoint =newEndpointImpl(springBus(),fileCxfService());
        endpoint.publish("/download");System.err.println("服务发布成功!地址为:http://localhost:7001/file/download?wsdl");return endpoint;}}

FileCxfService

该类指定了暴露的服务接口,注意类中的注解都很重要,不能丢,具体可以看说明

packagecom.example.webservice.service;importjavax.jws.WebMethod;importjavax.jws.WebParam;importjavax.jws.WebResult;importjavax.jws.WebService;importjavax.xml.ws.BindingType;@BindingType(value ="http://www.w3.org/2003/05/soap/bindings/HTTP/")@WebService(serviceName ="FileCxfService",// 与接口中指定的name一致
        targetNamespace ="http://webservice.example.com"// 与接口中的命名空间一致,一般是接口的包名倒)publicinterfaceFileCxfService{@WebMethod(operationName ="downloadFile")@WebResult(name ="String")StringdownloadFile(@WebParam(name ="params", targetNamespace ="http://webservice.example.com")String params,@WebParam(name ="token", targetNamespace ="http://webservice.example.com")String token);}

FileCxfServiceImpl

该类指定了暴露的服务接口的具体实现,注意类中的注解都很重要,不能丢,具体可以看说明

packagecom.example.webservice.service.impl;importcn.hutool.core.codec.Base64;importcom.alibaba.fastjson2.JSONObject;importcom.example.webservice.pojo.FileDto;importcom.example.webservice.service.FileCxfService;importjavax.jws.WebService;@WebService(serviceName ="FileCxfService",// 与接口中指定的name一致
        targetNamespace ="http://webservice.example.com"// 与接口中的命名空间一致,一般是接口的包名倒)publicclassFileCxfServiceImplimplementsFileCxfService{@OverridepublicStringdownloadFile(String params,String token){//下载文件System.err.println("params : "+ params);FileDto fileDto =JSONObject.parseObject(params,FileDto.class);System.err.println("fileDto : "+ fileDto);String data =null;try{
            data =Base64.encode("C:\\Users\\YIQI\\Desktop\\ebook\\Java70.pdf");}catch(Exception e){
            e.printStackTrace();}System.err.println(data);return data;}}

FileDto

该类为参数实体类,用于接受客户端传来的参数

packagecom.example.webservice.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.ToString;@Data@AllArgsConstructor@ToStringpublicclassFileDto{privateString fileId;privateString newFileId;privateString bucketName;}

客户端

在SpringBoot中整合WebService的客户端,需要指定服务端暴露的服务接口

项目结构

image-20230727184202714

配置

客户端POM

<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.3</version><relativePath/><!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>webclient</artifactId><version>0.0.1-SNAPSHOT</version><name>webclient</name><description>webclient</description><properties><java.version>17</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--cxf--><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-transports-http</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-frontend-jaxws</artifactId><version>3.5.1</version></dependency><!--hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.12</version></dependency><!--fastjson--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.16</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

客户端YML

server:# 可以不配置port:1000

FileCxfService

这个文件和服务端的FileCxfService保持一致,用于指定客户端请求的方式

packagecom.example.webclient.service;importjavax.jws.WebParam;importjavax.jws.WebService;@WebService(name ="FileCxfService",// 暴露服务名称
        targetNamespace ="http://webservice.example.com"// 命名空间,一般是接口的包名倒序)publicinterfaceFileCxfService{StringdownloadFile(@WebParam(name ="data", targetNamespace ="http://webservice.example.com")String data,@WebParam(name ="token", targetNamespace ="http://webservice.example.com")String token);}

FileCxfClient

这个类是客户端的主类,里面有发送WebService请求的方法

packagecom.example.webclient.client;importcn.hutool.core.codec.Base64;importcom.alibaba.fastjson2.JSONObject;importcom.example.webclient.pojo.FileDto;importcom.example.webclient.service.FileCxfService;importcom.example.webclient.util.ConvertBASE64;importjavax.xml.bind.DatatypeConverter;importjavax.xml.namespace.QName;importjavax.xml.ws.Service;importjava.net.URL;publicclassFileCxfClient{publicstaticvoidmain(String[] args)throwsException{// 创建wsdl的urlURL url =newURL("http://localhost:7001/file/download?wsdl");// 指定命名空间和服务名称QName qName =newQName("http://webservice.example.com","FileCxfService");Service service =Service.create(url, qName);// 通过getPort方法返回指定接口FileCxfService myServer = service.getPort(FileCxfService.class);// 调用方法返回数据FileDto fileDto =newFileDto();
        fileDto.setFileId("1");
        fileDto.setNewFileId("1");
        fileDto.setBucketName("book");String params =JSONObject.toJSONString(fileDto);Long st =System.currentTimeMillis();String file = myServer.downloadFile(params,"TOKEN:ABC");// 解析文件到本地// 可以解析成字节数组,如果服务端返回的也是字节数组的话byte[] decode=Base64.decode(file);// 也可以将Base64写入到本地文件中ConvertBASE64.decoderBase64File(file,"C:\\Users\\YIQI\\Desktop\\ebook\\demo70.pdf");System.err.println("decode : "+ decode.toString());System.err.println("result get file success!");System.err.println("cost time : "+(System.currentTimeMillis()- st)/1000+" s.");}}

FileDto

这个类是封装请求参数的实体类,和服务端的FileDto保持一致

packagecom.example.webclient.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importlombok.ToString;@Data@AllArgsConstructor@NoArgsConstructor@ToStringpublicclassFileDto{privateString fileId;privateString newFileId;privateString bucketName;}

ConvertBASE64

该类是Base64工具类,可以完成Base64字符串和文件的互换

packagecom.example.webclient.util;importcn.hutool.core.codec.Base64Decoder;importcn.hutool.core.codec.Base64Encoder;importcn.hutool.core.io.FileUtil;importcom.alibaba.fastjson2.JSONObject;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;publicclassConvertBASE64{/**
     * 将文件转成base64编码字符串
     *
     * @param path
     * @return
     * @throws Exception
     */publicstaticStringencodeBase64File(String path)throwsException{File file =newFile(path);FileInputStream inputFile =newFileInputStream(file);byte[] buffer =newbyte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();returnnewBase64Encoder().encode(buffer);}/**
     * 将base64编码字符串转成文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */publicstaticvoiddecoderBase64File(String base64Code,String targetPath)throwsException{byte[] buffer =Base64Decoder.decode(base64Code);FileOutputStream out =newFileOutputStream(targetPath);
        out.write(buffer);
        out.close();}/**
     * 将base64字节装成文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */publicstaticvoidtoFile(String base64Code,String targetPath)throwsException{byte[] buffer = base64Code.getBytes();FileOutputStream out =newFileOutputStream(targetPath);
        out.write(buffer);
        out.close();}publicstaticStringtoJson(Object obj){returnJSONObject.toJSONString(obj);}publicstaticObjecttoObject(StringJSONString,Class cls){returnJSONObject.parseObject(JSONString, cls);}publicstaticvoidwriteByteArrayToFile(File desFile,byte[] data)throwsIOException{FileUtil.writeBytes(data, desFile);}publicstaticbyte[]readFileToByteArray(File srcFile)throwsIOException{returnFileUtil.readBytes(srcFile);}publicstaticStringencode(String string){returnnewString(Base64Encoder.encode(string.getBytes()));}publicstaticvoidmain(String[] args){try{String a =encodeBase64File("C:\\Users\\YIQI\\Desktop\\工作文件\\bg2.jpg");// String base64Code = encodeBase64File("D:/0101-2011-qqqq.tif");System.out.println(a);decoderBase64File(a,"C:\\Users\\YIQI\\Desktop\\工作文件\\bg3.jpg");// toFile(base64Code, "D:\\three.txt");}catch(Exception e){
            e.printStackTrace();}}}

测试

先启动服务端,可以看到对外发布的服务

image-20230727190423700

在启动客户端给服务端发送请求的方法,可以看到服务端返回的数据

image-20230727190539581

因为我把从服务端获取的文件写入到了本地,所以可以在文件目录中看到该文件

image-20230727190638111

标签: spring boot 后端 java

本文转载自: https://blog.csdn.net/weixin_41405524/article/details/131966824
版权归原作者 BirdMan98 所有, 如有侵权,请联系我们删除。

“SpringBoot整合WebService”的评论:

还没有评论