SpringBoot——实现WebService接口服务端以及客户端开发

实现WebService接口的发布以及调用

我们经常需要在两个系统之间进行一些数据的交互,这时候我们就需要开发数据交互接口。

一般来说,遇到比较多的接口有HTTP接口、WebService接口、FTP文件传输。今天我要来学习一下在SpringBoot框架下进行简单的webservice接口的开发。

在网上跟着好多个教程做了好多遍,终于能走通。

一、服务端代码开发

创建了两个wbservice接口TestService和CatService。

1、pom依赖

导入相关的依赖包。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.1.6</version>
        </dependency>

2、接口类

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

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 15:26
 */
@WebService(name = "TestService", // 暴露服务名称
        targetNamespace = "http://server.webservice.Bag.admin.com"// 命名空间,一般是接口的包名倒序
)
public interface TestService {
    @WebMethod
    public String sendMessage(@WebParam(name = "username") String username);

    @WebMethod
    public boolean getFlag(@WebParam(name = "username") String username);
}

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

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 17:02
 */
@WebService(name = "CatService", // 暴露服务名称
        targetNamespace = "http://server.webservice.Bag.admin.com"// 命名空间,一般是接口的包名倒序
)
public interface CatService {
    @WebMethod
    public String message(@WebParam(name = "name") String name);
}

3、接口实现类

import com.admin.Bag.webservice.server.TestService;
import org.springframework.stereotype.Component;

import javax.jws.WebService;

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 15:31
 */
@WebService(serviceName = "TestService", // 与接口中指定的name一致
        targetNamespace = "http://server.webservice.Bag.admin.com", // 与接口中的命名空间一致,一般是接口的包名倒
        endpointInterface = "com.admin.Bag.webservice.server.TestService"// 接口地址
)
@Component
public class TestServiceImpl implements TestService {

    @Override
    public String sendMessage(String username) {
        return "=====Hello! " + username + "=====";
    }

    @Override
    public boolean getFlag(String username) {
        //
        return true;
    }
}
import com.admin.Bag.webservice.server.CatService;
import org.springframework.stereotype.Component;

import javax.jws.WebService;

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 17:05
 */
@WebService(serviceName = "CatService", // 与接口中指定的name一致
        targetNamespace = "http://server.webservice.Bag.admin.com", // 与接口中的命名空间一致,一般是接口的包名倒
        endpointInterface = "com.admin.Bag.webservice.server.CatService"// 接口地址
)
@Component
public class CatServiceImpl implements CatService {

    @Override
    public String message(String name) {
        //
        return "一只小猫猫";
    }
}

4、webservice配置文件

import com.admin.Bag.webservice.server.impl.CatServiceImpl;
import com.admin.Bag.webservice.server.impl.TestServiceImpl;
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;

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 15:37
 */
@Configuration
public class cxfConfig {
    @Bean
    public ServletRegistrationBean disServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new CXFServlet(), "/webService/*");
        return servletRegistrationBean;
    }
    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), new TestServiceImpl());
        endpoint.publish("/TestService");
        return endpoint;
    }
    @Bean
    public Endpoint endpoint2() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), new CatServiceImpl());
        endpoint.publish("/CatService");
        return endpoint;
    }

}

启动项目。我的项目端口号是8080。浏览器访问地址:http://localhost:8082/webService
可见接口信息CatService和TestService,点进链接可以看每个接口的wsdl文档。
在这里插入图片描述

2、客户端开发

客户端是一个单独的项目。

(1)pom依赖

不同的SpringBoot版本对应的依赖版本也不一样,我也是试了好久终于成了。我的SpringBoot版本号是2.3.0.RELEASE。

  <!-- 进行jaxes 服务开发 -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.0.1</version>
        </dependency>
        <!-- 内置jetty web服务器 -->
        <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http-jetty</artifactId>
        <version>3.0.1</version>
        </dependency>

(2)封装客户端方法clientUtil


import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 17:46
 */
public class clientUtil {

    public static String callWebSV(String wsdUrl, String operationName, String... params) throws Exception {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(wsdUrl);
        //client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects;
        // invoke("方法名",参数1,参数2,参数3....);
        objects = client.invoke(operationName, params);
        return objects[0].toString();
    }
}

(3)调用接口类

使用定时调用webservice接口。

import com.admin.webAppoint.webservice.client.clientUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zll
 * @version 1.0
 * @date 2020/6/10 17:50
 */
@RestController
@Component
public class TestController {
    //在一个方法中连续调用多次WebService接口,每次调用前需要重置上下文。
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    @Scheduled(cron="*/15 * * * * ?")
    public String getMessage()  {
        Thread.currentThread().setContextClassLoader(classLoader);//在获取连接之前 还原上下文
        System.out.println("======开始调用webservice接口=====");
        String url = "http://localhost:8082/webService/CatService?wsdl";
        String methodName = "message";
        System.out.println("Calling" + url);
        String result="";
        try {
            result=clientUtil.callWebSV(url, methodName, "name");
        } catch (Exception e) {
            System.err.println("接口调用失败!!!!");
            return "失败";
        }
        System.out.println("===Finished!===恭喜你啊!!!CatService接口调用成功!!!===获得的数据是:"+result);
        return "Finished!";
    }

    @Scheduled(cron="*/5 * * * * ?")
    public String getMessage2()  {
        Thread.currentThread().setContextClassLoader(classLoader);//在获取连接之前 还原上下文
        System.out.println("======开始调用webservice接口=====");
        String url = "http://localhost:8082/webService/TestService?wsdl";
        String methodName = "sendMessage";
        System.out.println("Calling" + url);
        String result="";
        try {
            result=clientUtil.callWebSV(url, methodName, "username");
        } catch (Exception e) {
            System.err.println("接口调用失败!!!!");
            return  "失败";
        }
        System.out.println("===Finished!===恭喜你啊!!!TestService接口调用成功!!!===获得的数据是:"+result);
        return "Finished!";
    }
}

(4)运行结果

首先启动服务端。启动客户端。

遇到过报错:
报错——使用cxf时报错:org.apache.cxf.interceptor.Fault: Marshalling Error: XXX is not known to this context

最终成功调用服务端的webservice接口:

在这里插入图片描述

  • 17
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
好的,我可以为您提供相关的步骤和代码示例。 首先,我们需要在Spring Boot项目中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> ``` 接着,我们需要创建一个WebService,可以在Spring Boot项目中创建一个新的类,例如: ```java import javax.jws.WebMethod; import javax.jws.WebService; @WebService public class MyWebService { @WebMethod public String sayHello(String name) { return "Hello, " + name + "!"; } } ``` 此时,我们已经创建了一个简单的WebService,其中包含一个`sayHello`方法,用于返回传入的参数加上一句问候语。 然后,我们需要在Spring Boot项目中添加一个配置类,用于配置WebService的相关信息,例如: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter; @Configuration public class WebServiceConfig { @Bean public SimpleJaxWsServiceExporter simpleJaxWsServiceExporter() { SimpleJaxWsServiceExporter exporter = new SimpleJaxWsServiceExporter(); exporter.setBaseAddress("http://localhost:8080/services/"); return exporter; } } ``` 在上述配置中,我们使用了`SimpleJaxWsServiceExporter`类,它可以自动将`@WebService`注解的类发布为WebService,并且可以使用`setBaseAddress`方法设置WebService的访问地址。 最后,我们可以使用Java客户端来访问我们创建的WebService,例如: ```java import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; public class MyWebServiceClient { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/services/MyWebService?wsdl"); QName qname = new QName("http://webservice.springboot.example.com/", "MyWebServiceService"); Service service = Service.create(url, qname); MyWebService myWebService = service.getPort(MyWebService.class); String result = myWebService.sayHello("World"); System.out.println(result); } } ``` 在上述代码中,我们使用了Java标准库中的`javax.xml.ws.Service`类来访问我们创建的WebService,并且使用了`MyWebService`接口调用`sayHello`方法。 以上就是使用Spring BootWebService搭建WebService服务端及使用Java客户端的简单示例,希望对您有所帮助。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值