Spring Boot + CXF 搭建WebService

1 篇文章 0 订阅
1 篇文章 0 订阅

Spring Boot + CXF 搭建 WebService


一. 搭建WebService微服务


项目结构如下

1.1. 设置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.wsw.cfx</groupId>
  <artifactId>cfx</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/>
  </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>
    <!--lombok-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.8</version>
    </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>

1.2. 配置 SpringBoot 启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootCFXApplication {
  public static void main(String[] args) {
    SpringApplication.run(SpringBootCFXApplication.class, args);
  }
}

1.3. 构建实体类对象

import java.io.Serializable;
import java.util.Date;
import lombok.Data;

public class User implements Serializable {
  private String userId;
  private String username;
  private String age;
  private Date updateTime;

  @Override
  public String toString() {
    return "User{" +
        "userId='" + userId + '\'' +
        ", username='" + username + '\'' +
        ", age='" + age + '\'' +
        ", updateTime=" + 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;
  }
}

1.4. 构建Service接口

import com.wsw.cfx.domain.User;
import java.util.ArrayList;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService(targetNamespace = "http://impl.service.cfx.wsw.com/")
public interface UserService {
  @WebMethod
  String getName(@WebParam(name = "userId") String userId);

  @WebMethod
  User getUser(String userId);

  @WebMethod
  ArrayList<User> getAlLUser();
}

1.5. 构建接口实现类

package com.wsw.cfx.service.impl;

import com.wsw.cfx.domain.User;
import com.wsw.cfx.service.UserService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import org.springframework.stereotype.Component;

@WebService(targetNamespace = "http://impl.service.cfx.wsw.com/", endpointInterface = "com.wsw.cfx.service.UserService")
@Component
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("1");
    user.setUsername("zhansan");
    user.setAge("10");
    user.setUpdateTime(new Date());
    userMap.put(user.getUserId(), user);

    user = new User();
    user.setUserId("2");
    user.setUsername("lisi");
    user.setAge("20");
    user.setUpdateTime(new Date());
    userMap.put(user.getUserId(), user);

    user = new User();
    user.setUserId("3");
    user.setUsername("wangwu");
    user.setAge("30");
    user.setUpdateTime(new Date());
    userMap.put(user.getUserId(), user);
  }

  @Override
  public String getName(String userId) {
    return "wsw-" + 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是当前需要实现接口的全称;

1.6. 服务发布类编写

package com.wsw.cfx.config;

import com.wsw.cfx.service.UserService;
import com.wsw.cfx.service.impl.UserServiceImpl;
import javax.xml.ws.Endpoint;
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.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@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 即可查询发布出去的接口文件;
PS:如果需要发布多个webservice,需要配置多个Config实现类文件

二.调用WebService接口

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

package com.wsw.cfx.client;

import com.wsw.cfx.domain.User;
import com.wsw.cfx.service.UserService;
import java.util.ArrayList;
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;

public class WebsServiceClient {

  //1. 动态调用
  public static void main(String[] args) throws Exception {
    JaxWsDynamicClientFactory dcfClient = JaxWsDynamicClientFactory.newInstance();
    Client client = dcfClient.createClient("http://localhost:8080/service/user?wsdl");

    Object[] objects = client.invoke("getUser", "1");
    System.out.println("*******" + objects[0].toString());

    Object[] objectall = client.invoke("getAlLUser");
    System.out.println("*******" + objectall[0].toString());
    main2(args);
    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("3");
    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("2");
    System.out.println("UserName:" + userResult.getUsername());
    ArrayList<User> users = userService.getAlLUser();

  }
}

2.2 通过接口地址生成wsdl文件调用WebService接口

2.2.1 创建存放WebService生成文件的文件夹
2.2.2 点击右键 -> WebService -> Generate Java Code From Wsdl

在这里插入图片描述

2.2.3 将WebService接口地址填入点击OK

在这里插入图片描述

2.2.4 生成WebService文件后删除其中的.class文件

在这里插入图片描述

2.2.5 调用WebService接口
package com.wsw.cfx.example;

import com.wsw.cfx.ws.User;
import com.wsw.cfx.ws.UserService;
import com.wsw.cfx.ws.UserServiceImplService;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.namespace.QName;

public class Service {
    private static String PATH = "D:\\IdeaProjectSpace\\cfx\\src\\main\\java\\com\\wsw\\cfx\\ws\\user.wsdl";

    public static void main(String[] args) throws Exception {
        //wsdl网络路径
        URL url = new File(PATH).toURI().toURL();
        //服务描述中服务端点的限定名称  两个参数分别为 命名空间 服务名
        UserServiceImplService userServiceImplService = new UserServiceImplService(url);
        UserService port = userServiceImplService.getUserServiceImplPort();
        List<User> alLUser = port.getAlLUser();
        for (User user : alLUser) {
               System.out.println(user.toString());
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值