0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Spring Cloud OpenFeign でサーバ間通信処理のサンプルを作ってみた。

Posted at

Spring Cloud OpenFeign とは

Springで簡単に通信処理を実現できるツール

サンプルのシステム構成図

・サーバ情報
Server①:localhost:8080
Server②:localhost:8090
image.png

実行内容

image.png
「localhost:8080/api/hello」をブラウザーで表示すると「Hello, World」と表示。
Server①がServer②に「Hello,」という文字を渡して、Server②の処理内で「Hello, World」に加工。
加工したデータをServer①が受け取ってUserに返却するだけのサンプルです。

Server①のソースコード
HelloController.java
package com.restfull.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.restfull.httpclient.HelloClient;
@RestController
public class HelloController {

	@Autowired
	private HelloClient helloClient;

	/**
	 * Getメソッドで処理を実行(http://localhost:8080/api/hello)
	 * 
	 * @return 表示メッセージ
	 */
	@GetMapping("api/hello")
	public String hello() {
		String parts = "Hello,";
	    String message = helloClient.Hello(parts);
		return message;
	}
}
HelloClient.java
package com.restfull.httpclient;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.restfull.config.FeignConfig;

@FeignClient(name = "hello", configuration = FeignConfig.class, url = "localhost:8090")
@Component
public interface HelloClient {
	@PostMapping(path = "/api/hello", produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.TEXT_PLAIN_VALUE)
	String Hello(@RequestBody String parts);
}
Server②のソースコード
HelloController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/** サンプルコントローラー */
@RestController
public class HelloController {

	/**
	 * Postメソッドで処理を実行(http://localhost:8090/api/hello)
	 * 
	 * @return レスポンスメッセージ
	 */
	@PostMapping("/api/hello")
	public String helloApi(@RequestBody(required = false) String parts) {
		parts = parts + " World";
		return parts;
	}
}

補足:port番号の切り替え

application.properties
server.port=8090
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?