Spring Cloud Feign實踐

在實踐過程當中遇到哪些問題?

一、當provider加上server.context-path,Feign客戶端該如何使用?java

二、如何解決上述問題致使的監控檢查url不對問題?spring

三、常見的配置信息有哪些?apache

若是您也有這些疑惑請往下看;tomcat

代碼實踐

1、各服務都加入Spring Cloud 依賴:

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR4</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-build-dependencies</artifactId>
                <version>1.3.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>


            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>3.3</version>
            </dependency>

        </dependencies>

    </dependencyManagement>

    <dependencies>
        <!-- provider、consume 客戶端引入-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <!-- eureka-server引入 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

    </dependencies>

2、編寫註冊中心 eureka-register:

application.properties配置:bash

server.port=8301
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/

#是否開啓自我保護
eureka.server.enable-self-preservation=false
#清理間隔(單位毫秒,默認是60*1000)
eureka.server.eviction-interval-timer-in-ms=5000

#eureka.instance.ipAddress=192.168.10.55
eureka.instance.preferIpAddress=true
#心跳間隔
eureka.instance.lease-renewal-interval-in-seconds=5
#即服務續約到期時間(缺省爲90s)
eureka.instance.lease-expiration-duration-in-seconds=10

編寫服務類:app

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

    private static final Logger logger = LoggerFactory.getLogger(EurekaApplication.class);

    public static void main(String[] args) {

       System.setProperty("spring.config.location", "classpath:conf/env/application.properties");
       SpringApplication.run(EurekaApplication.class, args);
       logger.info("start completed !");
    }

}

3、編寫服務提供者 rpc-demo-provider:

application.properties配置:ide

spring.application.name=rpc-demo-provider
server.context-path=/provider
server.port=8083
eureka.client.serviceUrl.defaultZone=http://192.168.10.55:8301/eureka/

#優先顯示IP作爲主機名
eureka.instance.prefer-ip-address=true

#eureka client間隔多久去拉取服務註冊信息,默認爲30秒
eureka.client.registry-fetch-interval-seconds=10
#心跳間隔
eureka.instance.lease-renewal-interval-in-seconds=5
#即服務續約到期時間(缺省爲90s)
eureka.lease-expiration-duration-in-seconds=10

#因爲加了context-path因此得修改下instance狀態地址,便於eureka server、spring admin等健康檢查
eureka.instance.statusPageUrlPath=${server.context-path}/info
eureka.instance.healthCheckUrlPath=${server.context-path}/health
eureka.instance.homePageUrl=${server.context-path}
eureka.instance.context-path=${server.context-path}
instance.metadata-map.management.context-path=${server.context-path}/actuator

#spring boot通常日誌配置
logging.file=rpc-demo-provider.log
logging.level.root=info    
logging.level.com.huize.framework=DEBUG
logging.pattern.file=%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
logging.pattern.console=%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
logging.file.max-size=100M
logging.file.max-history=2

編寫服務類:測試

@RestController
@RequestMapping("/user")
public class UserController{

    @RequestMapping("/sayHello")
    @Override
    public String sayHello() {

       return "hello feign";
    }

    @RequestMapping("/getUser")
    @Override
    public User getUser() {
      User user = new User();
      user.setAge(25);
      user.setBrithday(new Date());
      user.setName("張三");
      return user;
    }
}


@EnableEurekaClient
@SpringBootApplication
public class ProviderApplication {

    private final static Logger logger = LogManager.getLogger(ProviderApplication.class);

    public static void main(String[] args) {

       //修改application location
       System.setProperty("spring.config.location", "classpath:conf/env/application.properties");
       SpringApplication.run(ProviderApplication.class, args);
       logger.info("start completed !");

    }


}

4、編寫服務消費者 rpc-demo-consume:

application.properties配置:fetch

spring.application.name=rpc-demo-consume
server.port=8082
eureka.client.serviceUrl.defaultZone=http://192.168.10.55:8301/eureka/
eureka.instance.prefer-ip-address=true
#eureka client間隔多久去拉取服務註冊信息,默認爲30秒
eureka.client.registry-fetch-interval-seconds=10
#心跳間隔
eureka.instance.lease-renewal-interval-in-seconds=5
#即服務續約到期時間(缺省爲90s)
eureka.lease-expiration-duration-in-seconds=10

server.contextPath=/consume
server.tomcat.max-threads=500

編寫服務類:ui

/***
 ** 因爲服務提供者加了context-path 因此這得在服務名後加上path或者在後面的RequestMapping加上/provider/user/**
 **/
@FeignClient(name="rpc-demo-provider/provider")
public interface FeignDemoProvider {


    @RequestMapping("/user/sayHello")
    String sayHello();

    @RequestMapping("/user/getUser")
    User getUser();

}


@RestController
@RequestMapping("/consume/hello")
public class HelloCatfishController {

    @Autowired
    private HelloCatfishProvider helloProvider;


    @RequestMapping("/sayHello")
    public String sayHello() {
       return helloProvider.sayHello();
    }


    @RequestMapping("/getUser")
    public User getUser() {
       return helloProvider.getUser();
    }

}


@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class ConsumeApplication {

    private final static Logger logger = LogManager.getLogger(ConsumeApplication.class);

    public static void main(String[] args) {
       System.setProperty("spring.config.location", "classpath:conf/env/application.properties");
       SpringApplication.run(ConsumeApplication.class, args);
       logger.info("start completed !");

    }

}

5、測試:

分別啓動 eureka-register、 rpc-demo-provider、rpc-demo-consume 服務;

訪問:localhost:/8082/consume/hello/getUser 顯示以下:

{

"name": "張三",

"age": 25,

"brithday": 1530849865821

}

相關文章
相關標籤/搜索