1.引入依賴
compile "org.springframework.cloud:spring-cloud-starter-ribbon:${cloud_config}"
2.稍作配置
在bootstrap.yaml
中加入Eureka server
相關配置
spring:
cloud:
config:
uri: http://localhost:8888
profile: rabbit
name: appliaction
username: pkaq
password: pkaqx
3.添加注解
@EnableEurekaClient
4.來點代碼
啟動類代碼
@SpringBootApplication
@EnableEurekaClient
open class RibbonClientBooter: CommandLineRunner{
@Autowired
val builder: RestTemplateBuilder? = null
@Bean
// 這個是新加的注解,表示開啟robbin的負載均衡功能。
@LoadBalanced
open fun restTemplate(): RestTemplate {
return builder!!.build()
}
@Throws(Exception::class)
override fun run(vararg args: String) {
println(" --- --- --- [ Ribbon client started ] --- --- --- ")
}
}
fun main(args: Array<String>) {
org.springframework.boot.SpringApplication.run(org.pkaq.RibbonClientBooter::class.java, *args)
}
Controller代碼
@RestController
class RibbonController {
@Autowired
var restTemplate: RestTemplate? = null
@RequestMapping("/Ribbon")
fun say(): String {
val microServiceNode = "tiger"
val serviceName = "say"
val url = "http://${microServiceNode}/${serviceName}"
return restTemplate!!.getForObject(url, String::class.java)+" - > Ribbon"
}
}
可以看到這里已經不用通過注入LoadBalancerClient
獲取serviceInstance
的方式來拼接請求路徑了,這是因為,當一個被@LoadBalanced注解修飾的RestTemplate對象向外發起HTTP請求時,會被LoadBalancerInterceptor類的intercept函數所攔截。由于我們在使用RestTemplate時候采用了服務名作為host,所以直接從HttpRequest的URI對象中通過getHost()就可以拿到服務名,然后調用execute函數去根據服務名來選擇實例并發起實際的請求。
5.啟動服務,大功告成