Spring Boot结合CXF搭建WebService

需要依赖Maven的Pom清单

<
        
        
            org.apache.cxf
            cxf-rt-frontend-jaxws
            3.1.12
        
        
            org.apache.cxf
            cxf-rt-transports-http
            3.1.12
               

构建并发布服务

构建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 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 userMap = new HashMap();
    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 getAlLUser() {
        ArrayList 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 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 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/)的取值,是如下内容:

Spring Boot结合CXF搭建WebService_第1张图片

服务名称InvoiceService和InvoiceServiceSoap的取值:

Spring Boot结合CXF搭建WebService_第2张图片

 

https://www.cnblogs.com/xibei666/p/8970549.html

你可能感兴趣的:(服务器)