Spring Boot Ribbon Sample with Eureka

昨日のRibbon のsampleは、Eureka service discoveryを使っていないので、ちょっと修正して、Eureka service discoveryを使用。
こっちのほうが、設定は少なくて簡単でした。

イメージ図

f:id:tomoTaka:20180101085441p:plain

SayHelloEurekaController.java

以下の2箇所だけ修正

package com.example.eurekafeign.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class SayHelloEurekaController {
    @Autowired
    private RestTemplate restTemplate;

    @Bean
    @LoadBalanced   // 1. add @LoadBalanced annotation
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @RequestMapping("hello/eureka/{name}")
    public String hello(@PathVariable String name) {
        // 2. use Eureka service name greeting-service instead of hostname and port
        String greeting = this.restTemplate.getForObject("http://greeting-service/hello/" + name, String.class);
        return greeting + " from eureka";
    }
}

Response Sample

f:id:tomoTaka:20180101084234p:plain

code

github.com