學習SpringCloud之服務調用Feign

簡介

  • SpringCloudFeign是的作用是微服務間實現聲明式的調用。同時還整合了RibbonHystrix的功能。

  • 聲明式調用的好處在於,避免了像之前介紹Ribbon時使用RestTemplate調用服務那樣,需要拼接請求URL,包括請求參數。
    這樣不但減少出錯的機會,代碼上也比較整潔好閱讀和理解。

以下示例均基於SpringCloud的Greenwich.SR1版本,且需要依賴到之前介紹SpringCloud相關的文章

基礎依賴

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
    </dependencies>

因爲這次使用Consul作爲服務治理,所以也需要引入Consul的依賴。

FeignCommon

這個模塊主要是爲了聲明一些服務的接口,讓Provider和Consumer去引入使用。

@FeignClient("feign-provider", fallbackFactory = HelloServiceFallbackFactory::class)
interface HelloService {

    @RequestMapping("/hello")
    fun hello(@RequestParam("name") name: String): String

}

首先我們使用 @FeignClient 註解聲明一個服務接口。
第一個參數爲提供實現的服務名稱。
第二個參數則是爲了實現Hystrix的熔斷功能。

這需要提供一個實現了這個接口的類來提供Fallback結果。

@Component
class HelloServiceFallback : HelloService {

    override fun hello(name: String): String {
        return "fallback function: hello $name."
    }

}

留意到服務接口定義中,是使用了工廠模式,所以還需要一個定義一個工廠類。
使用時也可以不用工廠模式。

@Component
class HelloServiceFallbackFactory(val helloServiceFallback: HelloServiceFallback) : FallbackFactory<HelloService> {

    override fun create(throwable: Throwable?): HelloService {
        // 當出現錯誤時,打印錯誤信息。
        println("hello service fallback reason : ${throwable?.message ?: "unknown error."}")
        return helloServiceFallback
    }

}

FeignProvider

負責實現服務接口功能,先配置Consul地址並打開Hystrix功能。

server:
  port: 6613

spring:
  application:
    name: feign-provider
  cloud:
    consul:
      host: localhost
      port: 8500

feign:
  hystrix:
    enabled: true

留意到spring.application.name和服務接口定義時@FeignClient指定的服務名是一致的。

@RestController
class HelloServiceImpl : HelloService {

    @Value("\${server.port}")
    var port: String? = null

    override fun hello(name: String): String {
        return "response from $port: hello $name."
    }

}

實現中不用再去寫 @RequestMapping,只需要重寫接口就可以,因爲在服務定義的時候已經指定了。

接下來只要在啓動類中增加 @EnableFeignClients 註解啓動就可以了。

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
class FeignProviderStarter

fun main(args: Array<String>) {
    runApplication<FeignProviderStarter>(*args)
}

FeignConsumer

負責模擬服務調用,同樣先配置好應用信息。

server:
  port: 6614

spring:
  application:
    name: feign-customer
  cloud:
    consul:
      host: localhost
      port: 8500

feign:
  hystrix:
    enabled: true

然後創建一個Controller去調用。

@RestController
class DemoController {

    @Autowired
    lateinit var helloService: HelloService

    @RequestMapping("/hello")
    fun hello(@RequestParam("name") name: String): String {
        return helloService.hello(name)
    }

}

這裏有一點要注意,由於helloService這個Bean是啓動時注入的,編譯器無辦法知道導致了會報錯。
這個錯誤可以忽略,不影響啓動和使用。

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
class FeignCustomerStarter

fun main(args: Array<String>) {
    runApplication<FeignCustomerStarter>(*args)
}

啓動應用,訪問http://localhost:6614/hello?name=czb1n,如果feign-provider服務狀態正常時,會顯示response from 6613: hello czb1n.。否則會返回fallback function: hello czb1n.

其他

示例代碼地址: https://github.com/czb1n/learn-spring-cloud-with-kotlin

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章