RestTemplateを使用してサーバ間でapi通信を行う


簡単な説明


サーバ間でget方式でapi通信を行う方法

開発環境(IDE、言語、フレームワーク)


intellij, java, spring

システム設定


2台の
  • Apache Tomcatサーバ
    -apiサーバ:localhost 8090/apiserver
    -クライアントサーバ:localhost 8080/ClientServer
  • プロジェクト構造

  • api server
  • apiServer
      ├─src
        ├─main
        │  ├─java
        │  │  └─com
        │  │      └─base
        │  │          └─example
        │  │              └─menuMainAPI
        │  │                  ├─controller
        │  │                  ├─dao
        │  │                  ├─dto
        │  │                  └─service
        │  ├─resources
        │  └─webapp
        │      ├─static
        │      └─WEB-INF
        │          └─views
        └─test
            └─java
    
  • client server
  • serverClient
       ├─src
         ├─main
         │  ├─java
         │  │  └─com
         │  │      └─base
         │  │          └─example
         │  │              └─menuMainAPI
         │  │                  ├─controller
         │  │                  ├─dao
         │  │                  ├─dto
         │  │                  └─service
         │  ├─resources
         │  └─webapp
         │      ├─static
         │      └─WEB-INF
         │          └─views
         └─test
             └─java

    敵意


    共通
    <?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.base.example</groupId>
        <artifactId>serverClient</artifactId>
        <packaging>war</packaging>
        <version>1</version>
    
        <properties>
            <jdk.version>8</jdk.version><!--기본설정-->
            <spring.version>5.2.3.RELEASE</spring.version><!--기본설정-->
            <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version><!--기본설정-->
            <jcloverslf4j.version>1.7.31</jcloverslf4j.version><!--기본설정-->
            <logback.version>1.2.3</logback.version><!--기본설정-->
        </properties>
    
        <dependencies>
            <!--기본설정-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!--기본설정-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!--기본설정-->
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf-spring5</artifactId>
                <version>${thymeleaf.version}</version>
            </dependency>
    
            <!--기본설정-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>RELEASE</version>
                <scope>compile</scope>
            </dependency>
    
            <!--기본설정-->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>${jcloverslf4j.version}</version>
            </dependency>
    
            <!--기본설정-->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>${logback.version}</version>
            </dependency>
            <!--기본설정-->
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-core</artifactId>
                <version>9.0.48</version>
            </dependency>
            <!-- 기본설정 -->
            <!-- 기본설정 optional -->
            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.8.8</version>
            </dependency>
            <!--디펜던시 기본설정-->
    
            <!--db 설정-->
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.7</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.6</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-dbcp2</artifactId>
                <version>2.9.0</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6 -->
            <dependency>
                <groupId>com.oracle.database.jdbc</groupId>
                <artifactId>ojdbc6</artifactId>
                <version>11.2.0.4</version>
            </dependency>
    
        </dependencies>
    
    
        <build>
            <plugins>
                <!--플러그인 기본설정 시작-->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>${jdk.version}</source>
                        <target>${jdk.version}</target>
                    </configuration>
                </plugin>
                <!--플러그인 기본설정 끝-->
            </plugins>
        </build>
    </project>

    web.xml設定


    共通
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    
        <!--기본설정 시작-->
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--dispatcher 에 들어갈 지역변수-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/applicationContext.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <!--기본설정 종료-->
    
    
    </web-app>

    アプリケーションContext設定


    共通
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns="http://www.springframework.org/schema/beans"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--기본설정 시작-->
        <import resource="dispatcher-servlet.xml"/>
    
        <context:component-scan base-package="com.base.example.**"/>
    
        <!--마이바티스 설정-->
        <!--DB 설정 작업(오라클)-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    
            <!--로컬 테스트용-->
            <property name="url"
                      value="jdbc:oracle:thin:@0giri.com:1521:xe"/>
            <property name="username" value="KIL"/>
            <property name="password" value="3025"/>
        </bean>
        <!--마이바티스 설정 작업-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:mapper.xml"/>
        </bean>
    
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
    
        <!--기본설정 끝-->
    
    
    </beans>

    dispatcher-servlet設定


    共通
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns="http://www.springframework.org/schema/beans"
           xsi:schemaLocation="http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
        <!--spring - thymeleaf 기본설정 시작 -->
        <mvc:annotation-driven/>
    
        <mvc:resources mapping="/**" location="/static/"/>
    
    
        <bean id="templateResolver"
              class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    <!--        <property name="prefix" value="/WEB-INF/views/" />-->
    <!--        <property name="suffix" value=".html" />-->
            <property name="prefix" value="/WEB-INF/" />
            <!--뷰리졸버에서 utf-8로 반환할것을 설정-->
            <property name="characterEncoding" value="utf-8" />
            <property name="templateMode" value="HTML5" />
        </bean>
    
        <!--바로위의 id="templateResolver" 설정을 가져와서 타임리프에 적용-->
        <bean id="templateEngine"
              class="org.thymeleaf.spring5.SpringTemplateEngine">
            <property name="templateResolver" ref="templateResolver" />
        </bean>
    
        <!--templateEngine bean을 매개로 타임리프 엔진에 templateResolver 의 설정을 전달-->
        <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
            <property name="templateEngine" ref="templateEngine" />
            <!--뷰 리졸버에서 온 자료를 utf-8 형식으로 출력하게 설정-->
            <property name="characterEncoding" value="utf-8"/>
        </bean>
    
        <!--spring - thymeleaf 기본설정 끝-->
    
    
    </beans>

    コントローラ設定-apiServer

    package com.base.example.menuMainAPI.controller;
    
    import com.base.example.menuMainAPI.service.TestService;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.web.bind.annotation.*;
    
    @CrossOrigin(origins = "*")
    @RestController
    @RequestMapping(value = "res-api-test", produces ="application/json; charset=UTF-8")
    public class TestApiController {
        private static final Log LOG = LogFactory.getLog(TestApiController.class);
    
        TestService testService;
    
        TestApiController(TestService testService){
            this.testService = testService;
        }
    
        @GetMapping(value = "")
        public String getMainInfo() {
            LOG.info("yyy");
            return testService.makeJson();
        }
    
    }
    

    サービス設定-apiserver(オプション)

    package com.base.example.menuMainAPI.service;
    
    import com.base.example.menuMainAPI.dto.TestDto;
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.stereotype.Service;
    
    @Service
    public class TestService {
        private static final Log LOG = LogFactory.getLog(TestService.class);
    
        public String makeJson(){
            TestDto testDto = new TestDto();
            testDto.setTestNumber(1);
            testDto.setTestString("test");
            testDto.setTestBoolean(true);
    
            Gson gson = new Gson();
            JsonObject obj = new JsonObject();
            String jsonBuild = gson.toJson(testDto);
            LOG.info(jsonBuild);
            return jsonBuild;
        }
    }
    

    DAO設定-apiserver(オプション)


    none

    DTO設定-apiserver(オプション)

    package com.base.example.menuMainAPI.dto;
    
    public class TestDto {
        private Integer testNumber;
        private String testString;
        private Boolean testBoolean;
    
        public Integer getTestNumber() {
            return testNumber;
        }
    
        public void setTestNumber(Integer testNumber) {
            this.testNumber = testNumber;
        }
    
        public String getTestString() {
            return testString;
        }
    
        public void setTestString(String testString) {
            this.testString = testString;
        }
    
        public Boolean getTestBoolean() {
            return testBoolean;
        }
    
        public void setTestBoolean(Boolean testBoolean) {
            this.testBoolean = testBoolean;
        }
    }
    

    MybatisとJPA設定-apiserver(Optinal)


    mybatis-config

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
    
        <typeAliases>
    
        </typeAliases>
    
    </configuration>

    mapper

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="menuMain">
    
    </mapper>

    Javascript設定-apiserver


    none

    Html設定-apiserver


    none

    コントローラ設定-クライアントサーバ

    package com.base.example.menuMainAPI.controller;
    
    import com.base.example.menuMainAPI.service.RestTemplateService;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    @CrossOrigin(origins = "*")
    @RestController
    @RequestMapping(value = "req-test", produces ="application/json; charset=UTF-8")
    public class ClientController {
        private static final Log LOG = LogFactory.getLog(ClientController.class);
    
        RestTemplateService restTemplateService;
    
        ClientController(RestTemplateService restTemplateService){
            this.restTemplateService = restTemplateService;
        }
    
        @GetMapping(value = "/{menuMain}")
        public ResponseEntity<String> getMainInfo(@PathVariable(name="menuMain") String menuMain) {
            return ResponseEntity.ok(restTemplateService.hello());
        }
    
    }
    

    サービス設定-クライアントサーバ(オプション)

    package com.base.example.menuMainAPI.service;
    
    import com.base.example.menuMainAPI.dto.ClientTestDto;
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestTemplate;
    import org.springframework.web.util.UriComponentsBuilder;
    
    import java.net.URI;
    
    @Service
    public class RestTemplateService {
        private static final Log LOG = LogFactory.getLog(RestTemplateService.class);
        public RestTemplateService() {
        }
    
        //1. 스트링으로 받는 경우
        public String hello(){
            //다른서버에 데이터를 요청하기위해 uri를 만드는 코드
            URI uri = UriComponentsBuilder
                    .fromUriString("http://localhost:8090/apiServer/")
                    .path("res-api-test")
                    .encode()
                    .build()
                    .toUri();
            LOG.info(uri.toString());
            //다른서버에 데이터를 요청하기위해 uri를 만드는 코드
    
            //다른 서버에 데이터를 요청하고 받아오는 코드
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
            //다른 서버에 데이터를 요청하고 받아오는 코드
    
            //데이터를 확인하고 가공하는 코드
            //가져온 데이터를 dto에 대입하는 코드
            LOG.info(result.getStatusCode());
            LOG.info(result.getBody());
            Gson gson = new Gson();
            JsonObject obj;
            obj = (JsonObject) JsonParser.parseString(result.getBody());
            LOG.info(obj);
    
            //가져온 데이터를 dto에 대입하는 코드
            ClientTestDto clientTestDto = new ClientTestDto();
            clientTestDto.setClientTestNumber(obj.get("testNumber").getAsInt());//숫자를 가져올때
            clientTestDto.setClientTestString(obj.get("testString").getAsString());//문자열 가져올떼
            clientTestDto.setClientTestBoolean(obj.get("testBoolean").getAsBoolean());//불린값을 가져올때
            //가져온 데이터를 dto에 대입하는 코드
    
            String dtoresult = gson.toJson(clientTestDto);
            //가져온 데이터를 dto에 대입하는 코드
            //데이터를 확인하고 가공하는 코드
            return dtoresult;
        }
    }
    

    DAO設定-クライアントサーバ(オプション)


    none

    DTO設定-クライアントサーバ(オプション)

    package com.base.example.menuMainAPI.dto;
    
    public class ClientTestDto {
        private Integer clientTestNumber;
        private String clientTestString;
        private Boolean clientTestBoolean;
    
        public Integer getClientTestNumber() {
            return clientTestNumber;
        }
    
        public void setClientTestNumber(Integer clientTestNumber) {
            this.clientTestNumber = clientTestNumber;
        }
    
        public String getClientTestString() {
            return clientTestString;
        }
    
        public void setClientTestString(String clientTestString) {
            this.clientTestString = clientTestString;
        }
    
        public Boolean getClientTestBoolean() {
            return clientTestBoolean;
        }
    
        public void setClientTestBoolean(Boolean clientTestBoolean) {
            this.clientTestBoolean = clientTestBoolean;
        }
    }
    

    MybatisとJPAの設定-クライアントサーバ(Optinal)


    mybatis-config

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
    
        <typeAliases>
    
        </typeAliases>
    
    </configuration>

    mapper

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
    
        <typeAliases>
    
        </typeAliases>
    
    </configuration>

    Javascriptクライアントサーバの設定


    none

    Html-クライアントサーバの設定


    none

    結果