Spring boot webService 사용 방법 분석

7244 단어 SpringbootwebService
예전 에 한 회사 에서 프로젝트 를 웹 서 비 스 를 사 용 했 지만 얼마 있 지 않 았 습 니 다.그 때 는 다른 것 도 연구 하지 않 았 습 니 다.
이번에 도 이런 사용 장면 을 만 났 다.다른 사람 을 연결 하 는 한 사람의 얼굴 인식 서비스 가 필요 하 다.아무것도 없 는 상황 에서 상대방 은 뉴스 dl 의 주소 만 주 고 전 과정 을 스스로 연구 했다.
먼저 웹 서 비 스 를 통 해 자신의 이 해 를 말씀 드 리 겠 습 니 다.약간 웹 sockt 처럼 느껴 집 니 다.서버 를 실현 한 다음 에 클 라 이언 트 에서 서버 를 호출 하여 서버 의 작업 을 완성 할 수 있 습 니 다.
여 기 는 spring-boot 를 사용 합 니 다.
1.spring-boot 프로젝트 를 만 들 고 jar 패키지 도입
2.대상 을 만 듭 니 다.

<!-- web Services -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
 
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
      <version>3.2.7</version>
    </dependency>
서버 인터페이스 만 들 기

package com.sunzy.mywebservice;


import lombok.Getter;
import lombok.Setter;

/**auth : szy
 *time : 2020-01-03
 **/
@Getter
@Setter
public class Person {
  private Integer id;
  private String name;
  private String niceName;
  private Integer age;
  private Double height;
}
서버 구현 방법

package com.sunzy.mywebservice.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.sunzy.mywebservice.Person;
import com.sunzy.mywebservice.service.TestApiService;
import org.springframework.stereotype.Component;

import javax.jws.WebService;
import java.util.List;

/**auth : szy
 *time : 2020-01-03
 **/
@Component
@WebService(name = "testApiService",
    targetNamespace = "http://service.mywebservice.sunzy.com",
    endpointInterface = "com.sunzy.mywebservice.service.TestApiService",
    portName = "10000")
public class TestApiServiceImpl implements TestApiService {
  @Override
  public Person insertPersonInfo(String person) {
    System.out.println("         :person="+person);
    List<Person> list = JSONArray.parseArray(person, Person.class);
    //TODO     
    return list.get(0);
  }
}
파일 을 설정 하고 서 비 스 를 외부 에 개방 하여 사용 합 니 다.
여기까지 완 료 했 습 니 다.프로젝트 를 실행 합 니 다.방문 주소:http://localhost:8080/ws/testApiService?wsdl

서버 배치 가 성 공 했 음 을 표시 합 니 다.
그럼 다음은 클 라 이언 트 가 어떻게 방문 하 는 지 입 니 다.
새 항목 을 만 들 수 있 습 니 다.이 항목 을 사용 하여 호출 할 수 있 습 니 다.아이디어 로 wdl 을 분석 하여 해당 하 는 코드 를 생 성 합 니 다.
항목 선택

wsdl 을 통 해 자바 코드 를 생 성 합 니 다.

위 에 생 성 된 주 소 를 기입 하고 아래 면접 에서 가방 이름 을 기입 합 니 다.중요 한 것 은 여기 위의 주 소 는 효과적으로 접근 할 수 있어 야 합 니 다.그렇지 않 으 면 프로그램 이 물건 을 읽 을 수 없고 해석 은 말 할 것 도 없습니다.
코드 생 성 완료 후 코드 를 볼 수 있 습 니 다:

호출 방법,여 기 는 스스로 컨트롤 러 를 써 서 클 라 이언 트 를 모방 하여 호출 합 니 다.

package com.sunzy.mywebservice.controller;/**
 * @title: Hello
 * @projectName mywebservice
 * @description: TODO
 * @author :szy
 * @date 2020/1/3-15:44
 */

import com.sunzy.mywebservice.Person;
import com.sunzy.mywebservice.config.TestApiServiceImplService;
import com.sunzy.mywebservice.service.TestApiService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.util.Map;

/**auth : szy
 *time : 2020-01-03
 **/
@RestController
@RequestMapping("/adminWebservice")
public class Hello {

  //       
  @GetMapping(value="/sync")
  public String sync(@RequestParam(value="data") String data) throws Exception{

    //     
           String address = "http://localhost:8080/ws/testApiService?wsdl";
           //     
           JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
           //       
           jaxWsProxyFactoryBean.setAddress(address);
           //       
           jaxWsProxyFactoryBean.setServiceClass(TestApiService.class);
           //           
          TestApiService us = (TestApiService) jaxWsProxyFactoryBean.create();

           //     
           String userId = "[{\"name\":\"JACK\"},{\"name\":\"TOM\"}]";
           //                 
           Person person = us.insertPersonInfo(userId);
           System.out.println("    :" + person.toString());

    return "index";
  }



  //          
  @GetMapping(value="/dontest")
  public String dontest(@RequestParam(value="data") String data) throws Exception{

    JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    Client client = dcf.createClient("http://127.0.0.1:8080/ws/testApiService?wsdl");


    Object[] objects = new Object[0];

    try {
      // invoke("   ",  1,  2,  3....);
      //     
      String userId = "[{\"name\":\"JACK\"},{\"name\":\"TOM\"}]";
      objects = client.invoke("insertPersonInfo", userId);

      System.out.println("    :" + objects[0]);

    } catch (java.lang.Exception e) {
      e.printStackTrace();
    }

    return "index";
  }


  //          (            )
  @GetMapping(value="/dontest2")
  public String dontest2(@RequestParam(value="data") String data) throws Exception{

    //     
    TestApiServiceImplService serviceImplService = new TestApiServiceImplService();

    com.sunzy.mywebservice.config.TestApiService apiService = serviceImplService.get10000();
    String userId = "[{\"name\":\"  \"},{\"name\":\"  \"}]";

    com.sunzy.mywebservice.config.Person x = apiService.insertPersonInfo(userId);

    //        
    System.out.println("    :" + x.toString());

    return "index";
  }
}
potman 을 통 해 호출 성공 을 볼 수 있 습 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기