SpringBoot整合WebService

news2024/10/6 12:23:30

SpringBoot整合WebService

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

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

环境

SpringBoot2.7.3

Jdk17

服务端

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

项目结构

image-20230727183518916

配置

服务端POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="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服务暴露配置文件

package com.example.webservice.config;

import com.example.webservice.service.FileCxfService;
import com.example.webservice.service.impl.FileCxfServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
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.xml.ws.Endpoint;

@Configuration
public class FileCxfConfig {

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

    @Bean(name = "downloadFileBean")
    public ServletRegistrationBean dispatcherServlet() {
        ServletRegistrationBean wbsServlet = new ServletRegistrationBean(new CXFServlet(), "/file/*");
        return wbsServlet;
    }

    @Bean
    public FileCxfService fileCxfService() {
        return new FileCxfServiceImpl();
    }

    @Bean
    public Endpoint endpointPurchase(SpringBus springBus, FileCxfService fileCxfService) {
        EndpointImpl endpoint = new EndpointImpl(springBus(), fileCxfService());
        endpoint.publish("/download");
        System.err.println("服务发布成功!地址为:http://localhost:7001/file/download?wsdl");
        return endpoint;
    }
    
}

FileCxfService

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

package com.example.webservice.service;


import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.BindingType;

@BindingType(value = "http://www.w3.org/2003/05/soap/bindings/HTTP/")
@WebService(serviceName = "FileCxfService", // 与接口中指定的name一致
        targetNamespace = "http://webservice.example.com" // 与接口中的命名空间一致,一般是接口的包名倒
)
public interface FileCxfService {

    @WebMethod(operationName = "downloadFile")
    @WebResult(name = "String")
    String downloadFile(@WebParam(name = "params", targetNamespace = "http://webservice.example.com") String params,
                @WebParam(name = "token", targetNamespace = "http://webservice.example.com") String token);

}

FileCxfServiceImpl

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

package com.example.webservice.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSONObject;
import com.example.webservice.pojo.FileDto;
import com.example.webservice.service.FileCxfService;

import javax.jws.WebService;

@WebService(serviceName = "FileCxfService", // 与接口中指定的name一致
        targetNamespace = "http://webservice.example.com" // 与接口中的命名空间一致,一般是接口的包名倒
)
public class FileCxfServiceImpl implements FileCxfService {

    @Override
    public String downloadFile(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

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

package com.example.webservice.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;

@Data
@AllArgsConstructor
@ToString
public class FileDto {

    private String fileId;
    private String newFileId;
    private String bucketName;

}

客户端

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

项目结构

image-20230727184202714

配置

客户端POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="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保持一致,用于指定客户端请求的方式

package com.example.webclient.service;


import javax.jws.WebParam;
import javax.jws.WebService;

@WebService(name = "FileCxfService", // 暴露服务名称
        targetNamespace = "http://webservice.example.com"// 命名空间,一般是接口的包名倒序
)
public interface FileCxfService {

    String downloadFile(@WebParam(name = "data", targetNamespace = "http://webservice.example.com") String data,
                @WebParam(name = "token", targetNamespace = "http://webservice.example.com") String token);

}

FileCxfClient

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

package com.example.webclient.client;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSONObject;
import com.example.webclient.pojo.FileDto;
import com.example.webclient.service.FileCxfService;
import com.example.webclient.util.ConvertBASE64;

import javax.xml.bind.DatatypeConverter;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;


public class FileCxfClient {

    public static void main(String[] args) throws Exception {

        // 创建wsdl的url
        URL url = new URL("http://localhost:7001/file/download?wsdl");
        // 指定命名空间和服务名称
        QName qName = new QName("http://webservice.example.com", "FileCxfService");
        Service service = Service.create(url, qName);
        // 通过getPort方法返回指定接口
        FileCxfService myServer = service.getPort(FileCxfService.class);
        // 调用方法返回数据
        FileDto fileDto = new FileDto();
        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保持一致

package com.example.webclient.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class FileDto {

    private String fileId;
    private String newFileId;
    private String bucketName;

}

ConvertBASE64

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

package com.example.webclient.util;


import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ConvertBASE64 {

    /**
     * 将文件转成base64编码字符串
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new Base64Encoder().encode(buffer);
    }


    /**
     * 将base64编码字符串转成文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath)
            throws Exception {
        byte[] buffer = Base64Decoder.decode(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }


    /**
     * 将base64字节装成文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void toFile(String base64Code, String targetPath)
            throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }


    public static String toJson(Object obj) {
        return JSONObject.toJSONString(obj);
    }


    public static Object toObject(String JSONString, Class cls) {
        return JSONObject.parseObject(JSONString, cls);
    }


    public static void writeByteArrayToFile(File desFile, byte[] data)
            throws IOException {
        FileUtil.writeBytes(data, desFile);
    }


    public static byte[] readFileToByteArray(File srcFile)
            throws IOException {
        return FileUtil.readBytes(srcFile);
    }


    public static String encode(String string) {
        return new String(Base64Encoder.encode(string.getBytes()));

    }


    public static void main(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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/800750.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Neo4j图数据基本操作

Neo4j 文章目录 Neo4jCQL结点和关系增删改查匹配语句 根据标签匹配节点根据标签和属性匹配节点删除导入数据目前的问题菜谱解决的问题 命令行窗口 neo4j.bat console 导入rdf格式的文件 :GET /rdf/ping CALL n10s.graphconfig.init(); //初始化 call n10s.rdf.import.fetch(&q…

每日一题——两个链表的第一个公共结点

题目 输入两个无环的单向链表&#xff0c;找出它们的第一个公共结点&#xff0c;如果没有公共节点则返回空。&#xff08;注意因为传入数据是链表&#xff0c;所以错误测试数据的提示是用其他方式显示的&#xff0c;保证传入数据是正确的&#xff09; 数据范围&#xff1a; n≤…

LeetCode 75 第十一题(392)判断子序列

题目: 示例: 分析: 给两个字符串s和t,问s是不是t的子序列.即判断t中能不能提取出s(s有的元素,t都要有.并且字符的相对顺序不能变,如果字符的相对顺序能变的话就不能用双指针来做,而是要用哈希表了,可以参考力扣383赎金信这题). 这题虽然简单,但是是练习双指针的一个很好的题目…

【QT】Day3

1. 完成闹钟的实现&#xff1a; widgt.h #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QDebug> #include <QTimerEvent> //定时器事件处理函数 #include <QTime> //时间类 #include <QTextToSpeech> //文本转语音类头…

ARP协议(地址解析协议)详解

ARP协议&#xff08;地址解析协议&#xff09;详解 ARP协议的作用映射方式静态映射动态映射 ARP原理及流程ARP请求ARP响应 ARP协议报文首部 ARP协议的作用 ARP协议是“Address Resolution Protocol”&#xff08;地址解析协议&#xff09;的缩写。其作用是在以太网环境中&…

DataEase开源BI工具安装_数据全量_增量同步_大屏拖拽自动生成_多数据源支持_数据血缘分析---大数据工作笔记0183

我这里用的是Centos7.9安装的 可以通过uname -p来查看一下我们的电脑架构,可以看到是x86_64架构的 我们下第一个,这个是x86架构的,第二个arm架构的 然后解压到/opt/module中 然后再去重命名一下文件夹. 推荐200G 本地模式的功能比较多 推荐100G

喜报!麒麟信安操作系统通过GB18030-2022国家标准

《信息技术 中文编码字符集》强制性国家标准GB 18030-2022将于2023年8月1日起全面实施。麒麟信安积极推动电子信息产业标准化工作&#xff0c;快速完成标准适配&#xff0c;近日&#xff0c;麒麟信安服务器操作系统V3、麒麟信安桌面操作系统V3顺利通过GB18030-2022《信息技术 中…

【Linux后端服务器开发】数据链路层

目录 一、以太网 二、MAC地址 三、MTU 四、ARP协议 一、以太网 “以太网”不是一种具体的网路&#xff0c;而是一种技术标准&#xff1a;既包含了数据链路层的内容&#xff0c;也包含了一些物理层的内容&#xff0c;例如&#xff1a;规定了网络拓扑结构、访问控制方式、传…

【Matplotlib 绘制折线图】

使用 Matplotlib 绘制折线图 在数据可视化中&#xff0c;折线图是一种常见的图表类型&#xff0c;用于展示随着变量的变化&#xff0c;某个指标的趋势或关系。Python 的 Matplotlib 库为我们提供了方便易用的功能来绘制折线图。 绘制折线图 下面的代码展示了如何使用 Matplo…

AutoSAR系列讲解(实践篇)9.4-通信相关机制(下)

一、Deadline Monitoring 1、超时监控 Deadline Monitoring,超时监控。超时监控之前在Update Bit中也提到过,但是超时监控可以分为两个等级: IPDU级:当一个Rx IPDU没有在规定的时间内收到有效数据,就启动超时处理Signal级:就是之前我们说过的Update Bit的方式,如果没有…

利用Vector和鸿鹄搭建微服务应用的可观测性平台

一. 背景 1.1 什么是微服务应用 微服务应用由一组具有自治性的服务所组成&#xff0c;每一个服务只提供一类服务&#xff0c;这些服务一起协作以提供复杂的业务功能。相比于传统的单体应用&#xff0c;微服务应用是高度分布式的。如下图所示&#xff0c;即为一个典型的微服务应…

嵌入式软件—RK3568开发环境搭建

一、RK3568 1.1 开发板特点 BSP比较大&#xff0c;对于电脑内存和存储空间要求高 1.2 BSP BSP&#xff08;Board Support Package&#xff0c;板级支持包&#xff09;&#xff0c;类似于PC系统中BIOS和驱动程序的集合&#xff0c;BSP包含的范围更广&#xff0c;除了外设驱动…

20.2 HTML 常用标签

1. head头部标签 <head>标签用于定义网页的头部, 其中的内容是给浏览器读取和解析的, 并不在网页中直接显示给用户. <head>标签通常包含以下一些常见的子标签: - <title>: 定义网页的标题, 在浏览器的标题栏或标签页上显示. - <meta>: 用于设置网页的…

Kotlin知识点

Kotlin 是 Google 推荐的用于创建新 Android 应用的语言。使用 Kotlin&#xff0c;可以花更短的时间编写出更好的 Android 应用。 基础 Kotlin 程序必须具有主函数&#xff0c;这是 Kotlin 编译器在代码中开始编译的特定位置。主函数是程序的入口点&#xff0c;或者说是起点。…

java+springboot+mysql大学图书共享交流平台

项目介绍&#xff1a; 使用javassmmysql开发的大学图书共享交流平台&#xff0c;系统包含超级管理员&#xff0c;系统管理员、用户角色&#xff0c;功能如下&#xff1a; 用户&#xff1a;主要是前台功能使用&#xff0c;包括注册、登录&#xff1b;查看图书交流&#xff08;…

[学习笔记]全面掌握Django ORM

参考资料&#xff1a;全面掌握Django ORM 1.1 课程内容与导学 学习目标&#xff1a;独立使用django完成orm的开发 学习内容&#xff1a;Django ORM所有知识点 2.1 ORM介绍 ORM&#xff1a;Object-Relational Mapping Django的ORM详解 在django中&#xff0c;应用的文件夹…

陪玩接单小程序开发方案详解

陪玩接单小程序有哪些功能呢&#xff1f;游戏陪玩&#xff0c;电竞游戏发布需求&#xff0c;接单平台小程序开发。 一 推单师推单&#xff0c;陪玩师接单&#xff0c;推单师派单&#xff0c;在线支付。 二 陪玩师接单&#xff0c;我的陪玩订单&#xff0c;我的钱包&#xff0c;…

2.获取DOM元素

获取DOM元素就是利用JS选择页面中的标签元素 2.1 根据CSS选择器来获取DOM元素(重点) 2.1.1选择匹配的第一个元素 语法: document.querySelector( css选择器 )参数: 包含一个或多个有效的CSS选择器 字符串 返回值: CSS选择器匹配的第一个元素&#xff0c;一个HTMLElement对象…

docker基础7——harbor私有仓库

文章目录 一、基本了解二、搭建私有仓库2.1 基于官方镜像搭建2.2 基于harbor 一、基本了解 大部分企业都会搭建一个内部使用得私有仓库&#xff0c;用于保存docker镜像&#xff0c;包括镜像的层次结构和元数据。 Docker Registry分类&#xff1a; 企业版EE。官方docker hub仓库…

【雕爷学编程】MicroPython动手做(10)——零基础学MaixPy之神经网络KPU

早上百度搜“神经网络KPU”&#xff0c;查到与非网的一篇文章《一文读懂APU/BPU/CPU/DPU/EPU/FPU/GPU等处理器》&#xff0c;介绍各种处理器非常详细&#xff0c;关于“KPU”的内容如下&#xff1a; KPU Knowledge Processing Unit。 嘉楠耘智&#xff08;canaan&#xff09;号…