2016년 7월 24일 일요일

Declarative client by using feign client

You can declare the interface instead of using restTemplate directly.
So you can use that interface' method to request rest call to other server.
After setting up the eureka server named as eureka-server,
you can set the feign client as below.

- structure













- pom.xml



    4.0.0

    org.blog.test
    feign-project
    1.0-SNAPSHOT

    
        
            
                org.springframework.cloud
                spring-cloud-netflix
                1.1.2.RELEASE
                pom
                import
            
        
    

    
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        

        
            org.springframework.cloud
            spring-cloud-starter-feign
        

        
            org.springframework.boot
            spring-boot-starter-actuator
            1.3.6.RELEASE
        

    




- application.properties

server.port=8888
spring.application.name=eureka-client
logging.level.org.blog.test.EurekaServerClient=debug


- FeignConfig.java

package org.blog.test;

import feign.Logger;
import feign.Logger.Level;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    @Bean
    Level feignLoggerLevel() {
        return Level.FULL;
    }
}


- FeignClientApplication.java

package org.blog.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@RestController
public class FeignClientApplication {

    @Autowired
    public EurekaServerClient eurekaServerClient;

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

    @RequestMapping("/server/info")
    public String getServerInfo() {
        return eurekaServerClient.getServerInfo("client-1");
    }
}


- EurekaServerClient.java

package org.blog.test;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("eureka-server")
public interface EurekaServerClient {

    @RequestMapping("/hello/{serverId}")
    public String getServerInfo(@RequestParam("serverId") String serverId);
}


- result


댓글 없음 :

댓글 쓰기