Spring Cloud(二)服務消費(基礎)

2021-09-10 18:29:08 字數 2517 閱讀 1012

loadbalancerclient介面的命名中,我們就知道這是乙個負載均衡客戶端的抽象定義,下面我們就看看如何使用spring cloud提供的負載均衡器客戶端介面來實現服務的消費。

命名為eureka-consumer並在pom.xml中引入依賴(這裡省略了parentdependencymanagement的配置):

<?xml version="1.0" encoding="utf-8"?>

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.2.release

cn.fllday

eureka-consumer

0.0.1-snapshot

eureka-consumer

demo project for spring boot

1.8 greenwich.release

org.springframework.cloud

spring-cloud-starter-eureka

1.4.0.release

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-actuator

spring:

name: spring-cloud-consumer

server:

port: 10000

eureka:

client:

service-url:

defaultzone: http://localhost:8000/eureka/

建立應用主類。初始化resttemplate,用來真正發起rest請求。@enablediscoveryclient註解用來將當前應用加入到服務治理體系中。

package cn.fllday.eurekafeign;

import org.springframework.cloud.client.discovery.enablediscoveryclient;

import org.springframework.context.annotation.bean;

import org.springframework.web.client.resttemplate;

@enablediscoveryclient

@bean

public resttemplate resttemplate()

public static void main(string args)

}

建立乙個介面用來消費eureka-client提供的介面:

package cn.fllday.eurekafeign.controller;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.cloud.client.serviceinstance;

import org.springframework.cloud.client.loadbalancer.loadbalancerclient;

import org.springframework.web.bind.annotation.restcontroller;

import org.springframework.web.client.resttemplate;

@restcontroller

public class dccontroller

}

可以看到這裡,我們注入了loadbalancerclient和resttemplate,並在/consumer介面的實現中,先通過loadbalancerclient的choose函式來負載均衡的選出乙個eureka-client的服務例項,這個服務例項的基本資訊儲存在serviceinstance中,然後通過這些物件中的資訊拼接出訪問/dc介面的詳細位址,最後再利用resttemplate物件實現對服務提供者介面的呼叫。

在完成了上面你的**編寫之後,讀者可以將eureka-server、eureka-client、eureka-consumer都啟動起來,然後訪問http://localhost:10000/consumer,來跟蹤觀察eureka-consumer服務是如何消費eureka-client服務的/dc介面的

文章參考:

SpringCloud 二 服務註冊中心

總結 示例 pandas 是基於numpy 的一種工具,該工具是為了解決資料分析任務而建立的。如下 示例 import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns impo...

二 springcloud的服務註冊

專案中架構是react springcloud微服務,在專案中實際應用,因此再回過頭溫習一下,加深理解。一下內容是自己的理解如有錯誤請指錯,哈哈。eureka服務註冊與發現,把後端的所有微服務集中管理實現 server port 7001 eureka instance hostname peer1...

springcloud 二 微服務簡介

假設乙個場景 網上電影購票系統,涉及的模組有電影模組 訂單模組 使用者模組。在沒有微服務之前,我們的做法可能是,乙個專案,存放所有的模組資訊,當前,這種做法也沒有問題,可以實現功能,隨著我們的業務系統越來越大,量,還有使用者人群越來越大,這樣膿腫的專案,就會存在各種各樣的問題,維護成本,硬體成本,不...