• Spring Boot+CXF搭建WebService(转)


    概述

      最近项目用到在Spring boot下搭建WebService服务,对Java语言下的WebService了解甚少,而今抽个时间查阅资料整理下Spring Boot结合CXF打架WebService一般步骤与方法;本文章结合各个博客资料整理而成,如有雷同,谨记转载;

    Spring Boot WebService开发

    需要依赖Maven的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.dbgo</groupId>
        <artifactId>webservicedemo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
        <name>webservicedemo</name>
        <description>Demo project for Spring Boot</description>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.8.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--WerbService CXF依赖-->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxws</artifactId>
                <version>3.1.12</version>
            </dependency>
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-transports-http</artifactId>
                <version>3.1.12</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.5</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>

    构建并发布服务

    构建Model对象

    package com.dbgo.webservicedemo.Model;
    
    import java.io.Serializable;
    import java.util.Date;
    
    public class User implements Serializable {
        private static final long serialVersionUID = -5939599230753662529L;
        private String              userId;
        private String            username;
        private String            age;
        private Date              updateTime;
    
        public String getUserId() {
            return userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getAge() {
            return age;
        }
    
        public void setAge(String age) {
            this.age = age;
        }
    
        public Date getUpdateTime() {
            return updateTime;
        }
    
        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }
    }

    构建服务接口

    package com.dbgo.webservicedemo.service;
    
    import com.dbgo.webservicedemo.Model.User;
    
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import java.util.ArrayList;
    
    @WebService
    public interface UserService {
        @WebMethod
        String getName(@WebParam(name = "userId") String userId);
    
        @WebMethod
        User getUser(String userI);
    
        @WebMethod
        ArrayList<User> getAlLUser();
    }

    构建接口实现类

    package com.dbgo.webservicedemo.service;
    
    import com.dbgo.webservicedemo.Model.User;
    
    import javax.jws.WebService;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    @WebService(targetNamespace="http://service.webservicedemo.dbgo.com/",endpointInterface = "com.dbgo.webservicedemo.service.UserService")
    public class UserServiceImpl implements UserService {
        private Map<String, User> userMap = new HashMap<String, User>();
        public UserServiceImpl() {
            System.out.println("向实体类插入数据");
            User user = new User();
            user.setUserId("411001");
            user.setUsername("zhansan");
            user.setAge("20");
            user.setUpdateTime(new Date());
            userMap.put(user.getUserId(), user);
    
            user = new User();
            user.setUserId("411002");
            user.setUsername("lisi");
            user.setAge("30");
            user.setUpdateTime(new Date());
            userMap.put(user.getUserId(), user);
    
            user = new User();
            user.setUserId("411003");
            user.setUsername("wangwu");
            user.setAge("40");
            user.setUpdateTime(new Date());
            userMap.put(user.getUserId(), user);
        }
        @Override
        public String getName(String userId) {
            return "liyd-" + userId;
        }
        @Override
        public User getUser(String userId) {
            User user= userMap.get(userId);
            return user;
        }
    
        @Override
        public ArrayList<User> getAlLUser() {
            ArrayList<User> users=new ArrayList<>();
            userMap.forEach((key,value)->{users.add(value);});
            return users;
        }
    }

    备注说明:接口实现类名称前的注解targetNamespace是当前类实现接口所在包名称的反序(PS:加上反斜线),endpointInterface是当前需要实现接口的全称;@WebService(targetNamespace="http://service.webservicedemo.dbgo.com/",endpointInterface = "com.dbgo.webservicedemo.service.UserService")

    服务发布类编写

    package com.dbgo.webservicedemo;
    
    import com.dbgo.webservicedemo.service.UserService;
    import com.dbgo.webservicedemo.service.UserServiceImpl;
    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 WebServiceConfig {
    
        @Bean
        public ServletRegistrationBean dispatcherServlet(){
            return new ServletRegistrationBean(new CXFServlet(),"/service/*");//发布服务名称
        }
    
        @Bean(name = Bus.DEFAULT_BUS_ID)
        public SpringBus springBus()
        {
            return  new SpringBus();
        }
    
        @Bean
        public UserService userService()
        {
            return  new UserServiceImpl();
        }
    
        @Bean
        public Endpoint endpoint() {
            EndpointImpl endpoint=new EndpointImpl(springBus(), userService());//绑定要发布的服务
            endpoint.publish("/user"); //显示要发布的名称
            return endpoint;
        }
    }

    运行程序,输入 http://localhost:8080/service/user?wsdl 即可查询发布出去的接口文件;

    如果需要发布多个webservice,需要配置多个Config实现类文件;

    客户端调用服务

    基于cxf客户端调用WebService可以简单概述2中模式:动态调用和协议调用;

    package com.dbgo.webservicedemo;
    
    import com.dbgo.webservicedemo.Model.User;
    import com.dbgo.webservicedemo.service.UserService;
    import org.apache.cxf.endpoint.Client;
    import org.apache.cxf.frontend.ClientProxy;
    import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
    import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
    import org.apache.cxf.transport.http.HTTPConduit;
    import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
    
    import java.util.ArrayList;
    
    public class webserviceclient {
    
        //动态调用
        public static void main(String[] args) throws Exception {
            JaxWsDynamicClientFactory dcflient=JaxWsDynamicClientFactory.newInstance();
    
            Client client=dcflient.createClient("http://localhost:8080/service/user?wsdl");
    
            Object[] objects=client.invoke("getUser","411001");
            System.out.println("*******"+objects[0].toString());
    
            Object[] objectall=client.invoke("getAlLUser");
            System.out.println("*******"+objectall[0].toString());
    
            main3(args);
        }
    
    
        //调用方式二,通过接口协议获取数据类型
        public static void main2(String[] args) throws Exception {
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean=new JaxWsProxyFactoryBean();
            jaxWsProxyFactoryBean.setAddress("http://localhost:8080/service/user?wsdl");
            jaxWsProxyFactoryBean.setServiceClass(UserService.class);
    
            UserService userService=(UserService)jaxWsProxyFactoryBean.create();
            User userResult= userService.getUser("411001");
            System.out.println("UserName:"+userResult.getUsername());
            ArrayList<User> users=userService.getAlLUser();
    
        }
    
    
        //调用方式三,通过接口协议获取数据类型,设置链接超时和响应时间
        public static void main3(String[] args) throws Exception {
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean=new JaxWsProxyFactoryBean();
            jaxWsProxyFactoryBean.setAddress("http://localhost:8080/service/user?wsdl");
            jaxWsProxyFactoryBean.setServiceClass(UserService.class);
    
            UserService userService = (UserService) jaxWsProxyFactoryBean.create(); // 创建客户端对象
            Client proxy= ClientProxy.getClient(userService);
            HTTPConduit conduit=(HTTPConduit)proxy.getConduit();
            HTTPClientPolicy policy=new HTTPClientPolicy();
            policy.setConnectionTimeout(1000);
            policy.setReceiveTimeout(1000);
            conduit.setClient(policy);
    
            User userResult= userService.getUser("411001");
            System.out.println("UserName:"+userResult.getUsername());
            ArrayList<User> users=userService.getAlLUser();
    
        }
    }

     基于wsimport和JAX-WS调用Web Service接口

           使用Jdk原生态wsimport指令生成相应的接口文件,来调取webservice接口。操作如下:

    1、生成接口文件:cmd->wsimport -d . -s . -p acme.client http://127.0.0.1/Services/InvoiceService.asmx?WSDL  

    即可通过cmd命令生成相应的接口文件;

    参数说明:
    -d 指定生成输出文件的保存路径(.class文件,根据需要决定是否生成class文件)
    -s 指定生成的java源文件的保存路径(.java文件,根据需要决定是否生成java源文件)
    -p 指定生成的java类的包(package)名称
    http://127.0.0.1/Services/InvoiceService.asmx?WSDL URL地址,URL地址后面必须添加“?WSDL”参数。WSDL参数也可以是小写(wsdl)。

    2、配置调用相应的文件

    import java.net.MalformedURLException;  
    import java.net.URL;  
      
    import javax.xml.namespace.QName;  
      
    import com.opertion.wsimport.HiService;  
      
    /** 
     * 使用Service类进行调用 
     * @author Administrator 
     */  
    public class Service {  
        public static void main(String[] args) throws MalformedURLException {  
            //wsdl网络路径  
            URL url = new URL("http://127.0.0.1/Services/InvoiceService.asmx?WSDL");  
            //服务描述中服务端点的限定名称  两个参数分别为 命名空间 服务名  
            QName qName = new QName("http://tempuri.org/", "InvoiceService");  
            //创建服务对象  
            javax.xml.ws.Service service = javax.xml.ws.Service.create(url, qName);  
            //获得Hiservice的实现类对象   
            InvoiceService hiService = service.getPort(new QName("http://tempuri.org/","InvoiceServiceSoap"),InvoiceService.class);  
            //调用WebService方法  
            System.out.println(hiService.sayHi("xiaoming"));  
        }  
    }  

    注意事项:

    命名空间 (http://tempuri.org/)的取值,是如下内容:

    服务名称InvoiceService和InvoiceServiceSoap的取值:

    参考博客

    Spring boot+CXF开发WebService Demo https://www.cnblogs.com/fuxin41/p/6289162.html

    springboot1.5.4 集成cxf完整实例   https://www.cnblogs.com/xiaojf/p/7231529.html

    JAX-WS调用Web Service参考地址

    通过javax.xml.ws.Service的方式调用WebService  https://blog.csdn.net/syy19930112/article/details/17427165

    使用wsimport和JAX-WS调用Web Service接口 https://www.cnblogs.com/yitouniu/p/7640079.html#commentform

    完整Demo下载

  • 相关阅读:
    Spark Streaming 中管理 Kafka Offsets 的几种方式
    Kafka 在华泰证券的探索与实践
    Kafka 客户端是如何找到 leader 分区的
    关于Java中如何判断字符串是否为json格式
    关于JAVA递归遍历树级菜单结构
    关于JDK8 三种时间获取方法以及日期加减
    关于在Java里面,时间的一些业务
    关于Java的IO通信
    关于git同时提交到2个仓库gitee github
    关于JVM——工具(二)
  • 原文地址:https://www.cnblogs.com/xibei666/p/8970549.html
Copyright © 2020-2023  润新知