1. 程式人生 > >【Spring Cloud】Spring Cloud中文手冊

【Spring Cloud】Spring Cloud中文手冊

歡迎關注公眾號:

----------------------------------------------正文----------------------------------------------------

Spring Cloud Netflix

關於(about)

由於翻譯質量不高,所以合成為中英對照雙語版本,如有不當之處,可聯絡修正,感謝你的支援。

貢獻者(Contributor)

This project provides Netflix OSS integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms. With a few simple annotations you can quickly enable and configure the common patterns inside your application and build large distributed systems with battle-tested Netflix components. The patterns provided include Service Discovery (Eureka), Circuit Breaker (Hystrix), Intelligent Routing (Zuul) and Client Side Load Balancing (Ribbon).

該專案通過自動配置和繫結到Spring環境和其他Spring程式設計模型慣例,為Spring Boot應用程式提供Netflix OSS整合。 通過幾個簡單的註釋,您可以快速啟用和配置應用程式中的常見功能模組,並使用久經考驗的Netflix元件構建大型分散式系統。 提供的功能模組包括服務發現(Eureka),斷路器(Hystrix),智慧路由(Zuul)和客戶端負載均衡(Ribbon)。

服務發現:Eureka客戶端(Service Discovery: Eureka Clients)

Service Discovery is one of the key tenets of a microservice based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly available, with each server replicating state about the registered services to the others.

服務發現是microservice基礎架構的關鍵原則之一。試圖著手配置每個客戶端或某種格式的約定可以說是非常困難的和非常脆弱的。Eureka是Netflix服務發現的一種服務和客戶端。這種服務是可以被高可用性配置的和部署,並且在註冊的服務當中,每個服務的狀態可以互相複製給彼此。

註冊到Eureka(Registering with Eureka)

When a client registers with Eureka, it provides meta-data about itself such as host and port, health indicator URL, home page etc. Eureka receives heartbeat messages from each instance belonging to a service. If the heartbeat fails over a configurable timetable, the instance is normally removed from the registry.

當一個客戶端註冊到Eureka,它提供關於自己的元資料(諸如主機和埠,健康指標URL,首頁等)Eureka通過一個服務從各個例項接收心跳資訊。如果心跳接收失敗超過配置的時間,例項將會正常從註冊裡面移除。

Example eureka client:

eureka 客戶端例子:

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

(i.e. utterly normal Spring Boot app). In this example we use @EnableEurekaClient explicitly, but with only Eureka available you could also use @EnableDiscoveryClient. Configuration is required to locate the Eureka server. Example:

在這個例子裡我們使用 @EnableEurekaClient 來宣告, 但只有使 Eureka 生效還得 使用 @EnableDiscoveryClient。 配置要求 定位Eureka服務端。 例如:

application.yml

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

where "defaultZone" is a magic string fallback value that provides the service URL for any client that doesn’t express a preference (i.e. it’s a useful default).

"defaultZone"是一個神奇的字串回退值,它提供了服務的URL給任何客戶端,而這不意味優先順序。 (i.e. 是一個常用的預設值).

The default application name (service ID), virtual host and non-secure port, taken from the Environment, are${spring.application.name}${spring.application.name} and ${server.port} respectively.

預設應用名(服務ID),物理主機地址和非安全埠, 分別從環境的 ${spring.application.name}${spring.application.name}和 ${server.port} 獲取。

@EnableEurekaClient makes the app into both a Eureka "instance" (i.e. it registers itself) and a "client" (i.e. it can query the registry to locate other services). The instance behaviour is driven by eureka.instance.*configuration keys, but the defaults will be fine if you ensure that your application has a spring.application.name(this is the default for the Eureka service ID, or VIP).

@EnableEurekaClient 使Eureka做為一個例項(註冊直接)和客戶端(它能通過查詢註冊來定位其它服務)註冊到應用裡面。例項的行為由eureka.instance.*的配置項來決定,但是你最好確保你的spring.application.name有個預設值。(這是Eureka的預設ID或VIP)。

對Eureka服務的身份驗證(Authenticating with the Eureka Server)

HTTP basic authentication will be automatically added to your eureka client if one of theeureka.client.serviceUrl.defaultZone URLs has credentials embedded in it (curl style, like). For more complex needs you can create a @Bean of typeDiscoveryClientOptionalArgs and inject ClientFilter instances into it, all of which will be applied to the calls from the client to the server.

如果其中一個eureka.client.serviceUrl.defaultZone的url已經把憑證嵌入到它裡面,那麼HTTP基本的身份驗證將會被自動新增到你的eureka客戶端(curl風格,如 http://user:[email protected]:8761/eureka)。 對於更復雜的需求,您可以建立一個帶“@Bean”註解的“DiscoveryClientOptionalArgs”型別並且為它注入“ClientFilter”例項。

Because of a limitation in Eureka it isn’t possible to support per-server basic auth credentials, so only the first set that are found will be used.
由於Eureka的一個限制是不可能支援每個伺服器基本授權認證,所以只被發現的第一組會被使用。

健康指標和狀態頁面(Status Page and Health Indicator)

The status page and health indicators for a Eureka instance default to "/info" and "/health" respectively, which are the default locations of useful endpoints in a Spring Boot Actuator application. You need to change these, even for an Actuator application if you use a non-default context path or servlet path (e.g. server.servletPath=/foo) or management endpoint path (e.g. management.contextPath=/admin). Example:

健康指標和狀態頁面分別對應一個Eureka例項的"/health"和"/info",是在一個Spring Boot Actuator應用預設的配置位置中很有用的一個點。即便是一個Actuator應用,如果你使用非預設的上下文路徑或者servlet路徑(如server.servletPath=/foo)或管理端點的路徑(如management.contextPath=/admin),你都需要做出相應的改變。例如:

application.yml

eureka:
  instance:
    statusPageUrlPath: ${management.context-path}/info
    healthCheckUrlPath: ${management.context-path}/health

These links show up in the metadata that is consumed by clients, and used in some scenarios to decide whether to send requests to your application, so it’s helpful if they are accurate.

這些連結呈現出在元資料所消耗的客戶端,並且使用在某些情況下決定是否傳送請求給你應用程式,如果這些資訊準確的話它們是有用的。

註冊一個安全應用(Registering a Secure Application)

If your app wants to be contacted over HTTPS you can set two flags in the EurekaInstanceConfig, viz eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true] respectively. This will make Eureka publish instance information showing an explicit preference for secure communication. The Spring Cloud DiscoveryClient will always return an URI for a service configured this way, and the Eureka (native) instance information will have a secure health check URL.

如果你的應用想通過HTTPS被聯絡上你需要設定兩個標記,分別是EurekaInstanceConfig, viz eureka.instance.[nonSecurePortEnabled,securePortEnabled]=[false,true]。這將使Eureka推送例項的資訊展示一個顯式的安全通訊。Spring Cloud的DiscoveryClient將總是通過這種方式返回一個服務的配置的URI(), 並且Eureka例項(native)的資訊將有一個安全的健康檢查的URL。

Because of the way Eureka works internally, it will still publish a non-secure URL for status and home page unless you also override those explicitly. You can use placeholders to configure the eureka instance urls, e.g.

因為Eureka的內部工作方式,它將繼續推送一個非安全的URL的狀態和主頁,除非你還覆蓋那些宣告。你可以使用佔位符娶配置eureka例項的url。 例子:

application.yml

eureka:
  instance:
    statusPageUrl: https://${eureka.hostname}/info
    healthCheckUrl: https://${eureka.hostname}/health
    homePageUrl: https://${eureka.hostname}/

(Note that ${eureka.hostname} is a native placeholder only available in later versions of Eureka. You could achieve the same thing with Spring placeholders as well, e.g. using ${eureka.instance.hostName}.)

(請注意 ${eureka.hostname} 是一個原生佔位符只可用在以後的版本的Eureka.你也可以使用Spring的佔位符做同樣的事情, 例如使用 ${eureka.instance.hostName}.)

If your app is running behind a proxy, and the SSL termination is in the proxy (e.g. if you run in Cloud Foundry or other platforms as a service) then you will need to ensure that the proxy "forwarded" headers are intercepted and handled by the application. An embedded Tomcat container in a Spring Boot app does this automatically if it has explicit configuration for the 'X-Forwarded-\*` headers. A sign that you got this wrong will be that the links rendered by your app to itself will be wrong (the wrong host, port or protocol).
如果你的應用在慢於一個代理啟動執行,並且SSL終端在代理裡面(如:如果你的應用作為一個服務在Cloud Foundry或其它平臺上跑的話),那麼你將要確保應用能夠攔截和處理代理轉發的頭資訊。如果它明確配置有'X-Forwarded-\*`這類頭資訊的情況下,在一個Spring Boot應用裡面內嵌的Tomcat容器自動處理的。出現這個錯誤的原因,是因為你的應用程式提供的連結本身弄錯了。(錯誤的主機,埠,協議)。

Eureka 健康檢查(Eureka’s Health Checks)

By default, Eureka uses the client heartbeat to determine if a client is up. Unless specified otherwise the Discovery Client will not propagate the current health check status of the application per the Spring Boot Actuator. Which means that after successful registration Eureka will always announce that the application is in 'UP' state. This behaviour can be altered by enabling Eureka health checks, which results in propagating application status to Eureka. As a consequence every other application won’t be sending traffic to application in state other then 'UP'.

預設情況下,Eureka使用客戶端心跳來確定一個客戶端是否活著。除非另有指定Discovery Client不會傳播當前Spring Boot Actuator的應用效能的健康檢查狀態。也就是說在成功註冊Eureka後總會宣佈的應用程式在“UP”的狀態。這種傳送應用狀態給Eureka的行為將觸發Eureka的健康檢查。因此其他每個應用程式在其他狀態下不會給應用程式傳送通訊然後才‘UP’。

application.yml

eureka:
  client:
    healthcheck:
      enabled: true

If you require more control over the health checks, you may consider implementing your owncom.netflix.appinfo.HealthCheckHandler.

如果你有更多超出健康檢查的監控,你可以考慮實現自己的com.netflix.appinfo.HealthCheckHandler.

Eureka給客戶端和例項的元資料(Eureka Metadata for Instances and Clients)

It’s worth spending a bit of time understanding how the Eureka metadata works, so you can use it in a way that makes sense in your platform. There is standard metadata for things like hostname, IP address, port numbers, status page and health check. These are published in the service registry and used by clients to contact the services in a straightforward way. Additional metadata can be added to the instance registration in theeureka.instance.metadataMap, and this will be accessible in the remote clients, but in general will not change the behaviour of the client, unless it is made aware of the meaning of the metadata. There are a couple of special cases described below where Spring Cloud already assigns meaning to the metadata map.

值得花一點時間瞭解Eureka元資料是如何工作的,所以你可以使用它的方式在你的平臺是有意義的。有標準的元資料,如主機名、IP地址、埠號、狀態頁面和健康檢查。這些元資料在服務註冊和客戶端聯絡服務端時以一種簡單的方式被推送出去。額外的元資料可以被新增到例項註冊在eureka.instance.metadataMap裡面,並且這都是在遠端客戶端可訪問到的,但通常不會改變客戶的行為,除非它是識別到元資料的含義。有一些特殊的情況:Spring Cloud已經分配元資料對映的含義。

在 Cloudfoundry 使用 Eureka(Using Eureka on Cloudfoundry)

Cloudfoundry has a global router so that all instances of the same app have the same hostname (it’s the same in other PaaS solutions with a similar architecture). This isn’t necessarily a barrier to using Eureka, but if you use the router (recommended, or even mandatory depending on the way your platform was set up), you need to explicitly set the hostname and port numbers (secure or non-secure) so that they use the router. You might also want to use instance metadata so you can distinguish between the instances on the client (e.g. in a custom load balancer). By default, the eureka.instance.instanceId is vcap.application.instance_id. For example:

Cloudfoundry有總的路由,所有在同個應用的例項有相同的主機名(在其他PaaS解決方案有類似的架構和這一樣)。這不妨礙我們使用Eureka,但如果你使用路由(推薦,甚至強制性的根據您的平臺建立的方式),你需要顯式地設定主機名和埠號(安全或不安全的),以便他們使用路由器。您可能還希望使用例項元資料,這樣你就可以區分在客戶端例項(如:在一個定製的負載均衡器)。預設情況下,eureka.instance.instanceId相當於vcap.application.instance_id。例如:

application.yml

eureka:
  instance:
    hostname: ${vcap.application.uris[0]}
    nonSecurePort: 80

Depending on the way the security rules are set up in your Cloudfoundry instance, you might be able to register and use the IP address of the host VM for direct service-to-service calls. This feature is not (yet) available on Pivotal Web Services (PWS).

按照規則把安全規則設定在你的Cloudfoundry例項裡面,你就可以通過服務到服務的呼叫方式註冊和使用主機虛擬機器的IP地址。這個功能還沒有可以在關鍵的Web服務。 (PWS).

在AWS上使用Eureka(Using Eureka on AWS)

If the application is planned to be deployed to an AWS cloud, then the Eureka instance will have to be configured to be Amazon aware and this can be done by customizing the EurekaInstanceConfigBean the following way:

假如應用要計劃部署到AWS雲,那麼Eureka例項必須配置為亞馬遜可識別的並且可以通過以下方式定製 EurekaInstanceConfigBean:

@Bean
@Profile("!default")
public EurekaInstanceConfigBean eurekaInstanceConfig() {
  EurekaInstanceConfigBean b = new EurekaInstanceConfigBean();
  AmazonInfo info = AmazonInfo.Builder.newBuilder().autoBuild("eureka");
  b.setDataCenterInfo(info);
  return b;
}

修改Eureka例項ID(Changing the Eureka Instance ID)

A vanilla Netflix Eureka instance is registered with an ID that is equal to its host name (i.e. only one service per host). Spring Cloud Eureka provides a sensible default that looks like this:${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}. For example myhost:myappname:8080.

Netflix Eureka例項是一個身份證,等於其域名註冊(即只有一個服務/主機)。Spring Cloud Eureka提供了合理的預設值,看起來像這樣:${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}}。例如` Myhost:myappname:8080 `。

Using Spring Cloud you can override this by providing a unique identifier in eureka.instance.instanceId. For example:

使用Spring雲可以通過eureka.instance.instanceId提供一個惟一的識別符號覆蓋它:

application.yml

eureka:
  instance:
    instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}

With this metadata, and multiple service instances deployed on localhost, the random value will kick in there to make the instance unique. In Cloudfoundry the vcap.application.instance_id will be populated automatically in a Spring Boot application, so the random value will not be needed.

根據這種元資料,並且多個例項部署在localhost,隨機值可以確保例項的唯一。但是在Cloudfoundry中,vcap.application.instance_id將被自動賦值在一個Spring Boot應用程式中,因此隨機值將不再被需要。

使用EurekaClient(Using the EurekaClient)

Once you have an app that is @EnableDiscoveryClient (or @EnableEurekaClient) you can use it to discover service instances from the Eureka Server. One way to do that is to use the native com.netflix.discovery.EurekaClient (as opposed to the Spring Cloud DiscoveryClient), e.g.

一旦你有一個應用是 @EnableDiscoveryClient (或 @EnableEurekaClient) 你使用它從 Eureka Server發現服務例項。其中一個方法是使用原生的 com.netflix.discovery.EurekaClient (而不是 Spring Cloud的 DiscoveryClient), 例子:

@Autowired
private EurekaClient discoveryClient;

public String serviceUrl() {
    InstanceInfo instance = discoveryClient.getNextServerFromEureka("STORES", false);
    return instance.getHomePageUrl();
}

Don’t use the EurekaClient in @PostConstruct method or in a @Scheduled method (or anywhere where the ApplicationContext might not be started yet). It is initialized in a SmartLifecycle (withphase=0) so the earliest you can rely on it being available is in another SmartLifecycle with higher phase.

不要在@PostConstruct方法或@Scheduled方法使用EurekaClient(或任何ApplicationContext還沒被啟動的地方)。 它初始化 SmartLifecycle (在 phase=0下的情況下) ,所以你最先可以在另一個SmartLifecycle的更高階段依賴它生效。

代替原生的Netflix EurekaClient(Alternatives to the native Netflix EurekaClient)

You don’t have to use the raw Netflix EurekaClient and usually it is more convenient to use it behind a wrapper of some sort. Spring Cloud has support for Feign (a REST client builder) and also Spring RestTemplate using the logical Eureka service identifiers (VIPs) instead of physical URLs. To configure Ribbon with a fixed list of physical servers you can simply set <client>.ribbon.listOfServers to a comma-separated list of physical addresses (or hostnames), where <client> is the ID of the client.

你不一定要使用記憶體Netflix EurekaClient並且通常使用它背後的某種形式的封裝是更方便的。 Spring Cloud已經支援Feign(一個REST客戶端構建)並且Spring RestTemplate 也使用邏輯Eureka服務識別符號(VIP)代替物理的URL。去配置一個固定物理伺服器的列表的Ribbon,你可以對<client>是客戶端的ID,用一個逗號分隔實體地址(或主機名)列表來簡單地設定<client>.ribbon.listOfServers

You can also use the org.springframework.cloud.client.discovery.DiscoveryClient which provides a simple API for discovery clients that is not specific to Netflix, e.g.

你也可以使用org.springframework.cloud.client.discovery.DiscoveryClient提供一個簡單的API給不確定的Netflix發現客戶端。

@Autowired
private DiscoveryClient discoveryClient;

public String serviceUrl() {
    List<ServiceInstance> list = discoveryClient.getInstances("STORES");
    if (list != null && list.size() > 0 ) {
        return list.get(0).getUri();
    }
    return null;
}

為什麼註冊一個服務這麼慢? (Why is it so Slow to Register a Service?)

Being an instance also involves a periodic heartbeat to the registry (via the client’s serviceUrl) with default duration 30 seconds. A service is not available for discovery by clients until the instance, the server and the client all have the same metadata in their local cache (so it could take 3 heartbeats). You can change the period using eureka.instance.leaseRenewalIntervalInSeconds and this will speed up the process of getting clients connected to other services. In production it’s probably better to stick with the default because there are some computations internally in the server that make assumptions about the lease renewal period.

作為一個例項向註冊中心還包括一個預設持續30秒的週期心跳(通過客戶的serviceUrl)。一個服務對於客戶端的discovery不可用的,直到例項、服務端和客戶端全都擁有相同的元資料在它們的快取裡面(這可能還需要3次心跳)。你可以改變使用eureka.instance.leaseRenewalIntervalInSeconds並且這將加快這一程序的客戶端連線到其他服務。在實際生產中堅持預設可能是更好的,因為有一些在伺服器內部計算對租賃復興時期做出假設。

服務發現: Eureka Server(Service Discovery: Eureka Server)

Example eureka server (e.g. using spring-cloud-starter-eureka-server to set up the classpath):

例如 eureka 服務 (例子: 使用 spring-cloud-starter-eureka-server 去設定 classpath):

@SpringBootApplication
@EnableEurekaServer
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

The server has a home page with a UI, and HTTP API endpoints per the normal Eureka functionality under /eureka/*.

服務端有一個帶UI的首頁並且HTTP API端點按正常的Eureka功能下的/eureka/*

Due to Gradle’s dependency resolution rules and the lack of a parent bom feature, simply depending on spring-cloud-starter-eureka-server can cause failures on application startup. To remedy this the Spring Boot Gradle plugin must be added and the Spring cloud starter parent bom must be imported like so:

由於Gradle的依賴解析規則缺乏父依賴,單純的依靠spring-cloud-starter-eureka-server會導致啟動失敗。為了填補這一缺陷,必須新增Spring Boot Gradle外掛和匯入Spring cloud starter的父依賴,如:

build.gradle

buildscript {
  dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.5.RELEASE")
  }
}

apply plugin: "spring-boot"

應用“spring-boot”外掛

dependencyManagement {
  imports {
    mavenBom "org.springframework.cloud:spring-cloud-dependencies:Brixton.RELEASE"
  }
}

高可用性(High Availability, Zones and Regions)

The Eureka server does not have a backend store, but the service instances in the registry all have to send heartbeats to keep their registrations up to date (so this can be done in memory). Clients also have an in-memory cache of eureka registrations (so they don’t have to go to the registry for every single request to a service).

Eureka服務端沒有後臺儲存,但是服務例項在註冊裡面全都得傳送心跳去保持註冊更新(在記憶體裡操作)客戶端們也有一份記憶體快取著eureka的註冊資訊(因此,他們不必表為每單一的請求註冊到一個服務)。

By default every Eureka server is also a Eureka client and requires (at least one) service URL to locate a peer. If you don’t provide it the service will run and work, but it will shower your logs with a lot of noise about not being able to register with the peer.

預設情況下每個Eureka服務端也是一個Eureka客戶端並且通過請求服務的URL去定位一個節點。如果你不提供的話,服務雖然還會執行和工作,但是它不會向你列印一堆關於沒有註冊的節點日誌。

標準模式(Standalone Mode)

The combination of the two caches (client and server) and the heartbeats make a standalone Eureka server fairly resilient to failure, as long as there is some sort of monitor or elastic runtime keeping it alive (e.g. Cloud Foundry). In standalone mode, you might prefer to switch off the client side behaviour, so it doesn’t keep trying and failing to reach its peers. Example:

這兩個快取的組合(客戶端和伺服器)和心跳使一個標準模式的Eureka客戶端彈性掛掉,只要有某種monitor或者elastic執行保持它活著。(如 Cloud Foundry)在標準模式,您可能更傾向於關閉客戶端的行為,所以它不能保持失敗重試和重新找回它的那些節點。如:

application.yml (Standalone Eureka Server)

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Notice that the serviceUrl is pointing to the same host as the local instance.

請注意,serviceUrl是指向同一個主機的本地例項。

節點感知(Peer Awareness)

Eureka can be made even more resilient and available by running multiple instances and asking them to register with each other. In fact, this is the default behaviour, so all you need to do to make it work is add a valid serviceUrlto a peer, e.g.

Eureka甚至可以更有彈性和可用的執行多個例項,並讓他們互相註冊。事實上,這也是預設的行為,因此所有你需要讓它工作的,只要新增一個有效的節點serviceUrl,例如:

application.yml (Two Peer Aware Eureka Servers)

---
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1
  client:
    serviceUrl:
      defaultZone: http://peer2/eureka/

---
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2
  client:
    serviceUrl:
      defaultZone: http://peer1/eureka/

In this example we have a YAML file that can be used to run the same server on 2 hosts (peer1 and peer2), by running it in different Spring profiles. You could use this configuration to test the peer awareness on a single host (there’s not much value in doing that in production) by manipulating /etc/hosts to resolve the host names. In fact, the eureka.instance.hostname is not needed if you are running on a machine that knows its own hostname (it is looked up using java.net.InetAddress by default).

在這個例子,我們有一個YAML檔案能夠被使用去執行在兩個主機執行相同的服務(peer1 和 peer2),在不同的Spring配置檔案執行。你還可以使用這個配置在單個主機上去測試節點感知(在生產中這樣做沒有多少價值),通過操縱/etc/hosts來解決主機名稱。事實上,如果你在一直已知主機名的機器聲執行的話,eureka.instance.hostname是不需要的(預設查詢使用的java.net.InetAddress)。

You can add multiple peers to a system, and as long as they are all connected to each other by at least one edge, they will synchronize the registrations amongst themselves. If the peers are physically separated (inside a data centre or between multiple data centres) then the system can in principle survive split-brain type failures.

你可以新增更多的節點進一個系統,並且只要他們全都互相能通過最少一邊來互相連線,他們將同步互相註冊他們自己。如果節點被分離(在一個數據中心或者多個數據中心之間)那麼系統原則上split-brain型別存活失敗。

IP偏好(Prefer IP Address)

In some cases, it is preferable for Eureka to advertise the IP Adresses of services rather than the hostname. Seteureka.instance.preferIpAddress to true and when the application registers with eureka, it will use its IP Address rather than its hostname.

在一些案例裡,更可取的是Eureka廣播服務的IP地址而不是主機名。設定eureka.instance.preferIpAddress 為true以便當應用註冊到eureka的溼乎乎,它將使用它的IP地址而不是主機名。

斷路器(Circuit Breaker: Hystrix Clients)

Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.

Netflix意見建立了一個庫叫 Hystrix 實現了 circuit breaker pattern。 在microservice架構中有多個層的服務呼叫。

HystrixGraph.png

Figure 1. Microservice Graph

A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service reach a certain threshold (20 failures in 5 seconds is the default in Hystrix), the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer.

一個低水平的服務群中一個服務掛掉會給使用者導致級聯失效的。當呼叫一個特定的服務達到一定閾值(在Hystrix裡預設是5秒內20個失敗),斷路由開啟並且呼叫沒有成功的。開發人員能夠提供錯誤原因和開啟一個斷路由回撥。

HystrixFallback.png

Figure 2. Hystrix fallback prevents cascading failures

Having an open circuit stops cascading failures and allows overwhelmed or failing services time to heal. The fallback can be another Hystrix protected call, static data or a sane empty value. Fallbacks may be chained so the first fallback makes some other business call which in turn falls back to static data.

出現公開的電路停止連鎖故障並且允許解決或者失敗的服務時間來修復。回撥能被另一個Hystrix保護呼叫,靜態資料或者合理的空資料。回撥 可以繫結因此第一次回撥會有一些其它的業務呼叫反過來才落回到靜態資料。

Example boot app:

啟動應用示例:

@SpringBootApplication
@EnableCircuitBreaker
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

@Component
public class StoreIntegration {

    @HystrixCommand(fallbackMethod = "defaultStores")
    public Object getStores(Map<String, Object> parameters) {
        //do stuff that might fail
    }

    public Object defaultStores(Map<String, Object> parameters) {
        return /* something useful */;
    }
}

The @HystrixCommand is provided by a Netflix contrib library called "javanica". Spring Cloud automatically wraps Spring beans with that annotation in a proxy that is connected to the Hystrix circuit breaker. The circuit breaker calculates when to open and close the circuit, and what to do in case of a failure.

Netflix路由庫提供@HystrixCommand呼叫 "javanica". Spring Cloud 在這個註解下自動包裹Spring beans進一個代理裡面,被連線到了一個Hystrix斷路由。斷路器計算何時開啟和關閉電路,並在失敗的情況下做什麼。

To configure the @HystrixCommand you can use the commandProperties attribute with a list of @HystrixPropertyannotations. See here for more details. See the Hystrix wiki for details on the properties available.

你可以使用commandProperties引數和@HystrixProperty註解的集合來配置@HystrixCommand。請見 here 更多細節. 請見 theHystrix wiki 有關可用的屬性。

傳播安全上下文或使用 Spring Scopes(Propagating the Security Context or using Spring Scopes)

If you want some thread local context to propagate into a @HystrixCommand the default declaration will not work because it executes the command in a thread pool (in case of timeouts). You can switch Hystrix to use the same thread as the caller using some configuration, or directly in the annotation, by asking it to use a different "Isolation Strategy". For example:

如果你想一些執行緒的本地的上下文傳播到一個@HystrixCommand,預設宣告將不會工作,因為他線上程池裡執行命令。(在超時的情況下)。你可以切換Hystrix去使用同個執行緒讓呼叫者使用一些配置,或直接在註解中,讓它去使用不同的“隔離策略”。舉例:

@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
)
...

The same thing applies if you are using @SessionScope or @RequestScope. You will know when you need to do this because of a runtime exception that says it can’t find the scoped context.

如果你使用@SessionScope 或 @RequestScope同樣適用。你會知道你要這麼做,因為一個runtime異常說他不能找到作用域上下文。

健康指標(Health Indicator)

The state of the connected circuit breakers are also exposed in the /health endpoint of the calling application.

連線的斷路器的狀態也暴露在呼叫應用程式的/health端點中。

{
    "hystrix": {
        "openCircuitBreakers": [
            "StoreIntegration::getStoresByLocationLink"
        ],
        "status": "CIRCUIT_OPEN"
    },
    "status": "UP"
}

Hystrix 指標流(Hystrix Metrics Stream)

To enable the Hystrix metrics stream include a dependency on spring-boot-starter-actuator. This will expose the/hystrix.stream as a management endpoint.

使Hystrix指標流包括依賴於spring-boot-starter-actuator。這將使/hystrix.stream流作為一個管理端點。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

斷路器: Hystrix 儀表盤(Circuit Breaker: Hystrix Dashboard)

One of the main benefits of Hystrix is the set of metrics it gathers about each HystrixCommand. The Hystrix Dashboard displays the health of each circuit breaker in an efficient manner.

Hystrix的主要作用是會採集每一個HystrixCommand的資訊指標,把每一個斷路器的資訊指標顯示的Hystrix儀表盤上。

Hystrix.png

Figure 3. Hystrix Dashboard

To run the Hystrix Dashboard annotate your Spring Boot main class with @EnableHystrixDashboard. You then visit/hystrix and point the dashboard to an individual instances /hystrix.stream endpoint in a Hystrix client application.

執行Hystrix儀表板需要在spring boot主類上標註@EnableHystrixDashboard。然後訪問/hystrix檢視儀表盤,在hystrix客戶端應用使用/hystrix.stream監控。

Turbine

Looking at an individual instances Hystrix data is not very useful in terms of the overall health of the system.Turbine is an application that aggregates all of the relevant /hystrix.stream endpoints into a combined/turbine.stream for use in the Hystrix Dashboard. Individual instances are located via Eureka. Running Turbine is as simple as annotating your main class with the @EnableTurbine annotation (e.g. using spring-cloud-starter-turbine to set up the classpath). All of the documented configuration properties from the Turbine 1 wiki apply. The only difference is that the turbine.instanceUrlSuffix does not need the port prepended as this is handled automatically unless turbine.instanceInsertPort=false.

看一個例項Hystrix資料對於整個系統的健康不是很有用. Turbine 是一個應用程式,該應用程式彙集了所有相關的/hystrix.stream端點到 /turbine.stream用於Hystrix儀表板。執行turbine使用@EnableTurbine註解你的主類,使用spring-cloud-starter-turbine這個jar。配置請參考 the Turbine 1 wiki 唯一的區別是turbine.instanceUrlSuffix不需要埠號字首,因為這是自動處理,除非turbine.instanceInsertPort=false

The configuration key turbine.appConfig is a list of eureka serviceIds that turbine will use to lookup instances. The turbine stream is then used in the Hystrix dashboard using a url that looks like: (the cluster parameter can be omitted if the name is "default"). The cluster parameter must match an entry in turbine.aggregator.clusterConfig. Values returned from eureka are uppercase, thus we expect this example to work if there is an app registered with Eureka called "customers":

turbine.appConfig配置是一個eureka服務ID列表,turbine將使用這個配置查詢例項。turbine stream在hystrix dashboard中使用如下的url配置: http://my.turbine.server:8080/turbine.stream?cluster=<CLUSTERNAME>,如果叢集的名稱是default,叢集引數可以忽略)。這個cluster引數必須和turbine.aggregator.clusterConfig匹配。從eureka返回的值都是大寫的,因此我們希望下面的例子可以工作,如果一個app使用eureka註冊,並且被叫做"customers":

turbine:
  aggregator:
    clusterConfig: CUSTOMERS
  appConfig: customers

The clusterName can be customized by a SPEL expression in turbine.clusterNameExpression with root an instance ofInstanceInfo. The default value is appName, which means that the Eureka serviceId ends up as the cluster key (i.e. the InstanceInfo for customers has an appName of "CUSTOMERS"). A different example would beturbine.clusterNameExpression=aSGName, which would get the cluster name from the AWS ASG name. Another example:

clusterName可以使用SPEL表示式定義,在turbine.clusterNameExpression。 預設值是appName,意思是eureka服務ID最終將作為叢集的key,例如customers的 InstanceInfo有一個CUSTOMERS的appName。另外一個例子是turbine.clusterNameExpression=aSGName,將從AWS ASG name獲取叢集名稱。作者例子:

turbine:
  aggregator:
    clusterConfig: SYSTEM,USER
  appConfig: customers,stores,ui,admin
  clusterNameExpression: metadata['cluster']

In this case, the cluster name from 4 services is pulled from their metadata map, and is expected to have values that include "SYSTEM" and "USER".

在這種情況下,叢集名稱從4個服務從其元資料對映,期望包含“SYSTEM”和“USER”。

To use the "default" cluster for all apps you need a string literal expression (with single quotes, and escaped with double quotes if it is in YAML as well):

所有的app使用default,你需要一個文字表達式(使用單引號):

turbine:
  appConfig: customers,stores
  clusterNameExpression: "'default'"

Spring Cloud provides a spring-cloud-starter-turbine that has all the dependencies you need to get a Turbine server running. Just create a Spring Boot application and annotate it with @EnableTurbine.

spring cloud提供一個spring-cloud-starter-turbine,所有依賴項你需要執行一個turbine伺服器。使用@EnableTurbine建立一個spring boot應用。

by default Spring Cloud allows Turbine to use the host and port to allow multiple processes per host, per cluster. If you want the native Netflix behaviour built into Turbine that does not allow multiple processes per host, per cluster (the key to the instance id is the hostname), then set the propertyturbine.combineHostPort=false.
預設情況下Spring Cloud 允許 Turbine 在叢集的每個主機下使用主機名和埠執行多個程序。如果你想在叢集中的每個主機使用本機原生Netfix行為且不允許多個程序建立執行Turbine。(例項id的key為主機名)然後設定屬性turbine.combineHostPort=false

Turbine Stream

In some environments (e.g. in a PaaS setting), the classic Turbine model of pulling metrics from all the distributed Hystrix commands doesn’t work. In that case you might want to have your Hystrix commands push metrics to Turbine, and Spring Cloud enables that with messaging. All you need to do on the client is add a dependency to spring-cloud-netflix-hystrix-stream and the spring-cloud-starter-stream-* of your choice (see Spring Cloud Stream documentation for details on the brokers, and how to configure the client credentials, but it should work out of the box for a local broker).

在一些環境(Pass), 在所有分散式下典型的Turbine 模型的Hystrix 命令都不工作,在這種情況下,你可能想要 Hystrix 命令 推送到 Tuibine, 和Spring Cloud進行訊息傳遞,那麼你需要要做的是在客戶端新增一個依賴spring-cloud-netflix-hystrix-stream和你所選擇的 spring-cloud-starter-stream-*的依賴(相關資訊請檢視 Spring Cloud Stream 方檔,以及如何配置客戶端憑證,和工作時的要本地代理)

On the server side Just create a Spring Boot application and annotate it with @EnableTurbineStream and by default it will come up on port 8989 (point your Hystrix dashboard to that port, any path). You can customize the port using either server.port or turbine.stream.port. If you have spring-boot-starter-web and spring-boot-starter-actuator on the classpath as well, then you can open up the Actuator endpoints on a separate port (with Tomcat by default) by providing a management.port which is different.

建立一個帶有註解 @EnableTurbineStream 的Spring boot 應用伺服器,埠預設 8989 (Hystrix 儀表盤的URL都使用此埠), 如果你想自定義埠,可以配置 server.port 或 turbine.stream.port 任一個,如果你使用了 spring-boot-starter-web 和spring-boot-starter-actuator ,那麼你可以提供(使用Tomcat預設情況下) management.port 不同的埠,並開啟這個單獨的執行器埠

You can then point the Hystrix Dashboard to the Turbine Stream Server instead of individual Hystrix streams. If Turbine Stream is running on port 8989 on myhost, then put  in the stream input field in the Hystrix Dashboard. Circuits will be prefixed by their respective serviceId, followed by a dot, then the circuit name.

你可以把Dashboard指向Turbine Stream Server來代替個別Hystrix streams。如果Tubine Stream 使用你本機的8989埠執行,然後把 在流輸入欄位Hystrix儀表板 Circuits 將由各自的 serverId關綴,緊隨其後的是一個點,然後是circuit 名稱

Spring Cloud provides a spring-cloud-starter-turbine-stream that has all the dependencies you need to get a Turbine Stream server running - just add the Stream binder of your choice, e.g. spring-cloud-starter-stream-rabbit. You need Java 8 to run the app because it is Netty-based.

Spring Cloud提供了一個 spring-cloud-starter-turbine-stream,包括了執行 Turibine Stream Server執行所需要的所有依賴,如spring-cloud-starter-stream-rabbit. 因為使用了Netty-based,所以你需要Java 8 執行此應用

客戶端負載均衡器(Client Side Load Balancer: Ribbon)

Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.

Ribbon 是一個客戶端負載均衡器,給了你很多控制 HTTP 和 TCP 客戶端的行為,假裝已經使用了 Ribbon, 如果您使用的是@FeignClient那麼這一節還適用。

A central concept in Ribbon is that of the named client. Each load balancer is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer (e.g. using the @FeignClient annotation). Spring Cloud creates a new ensemble as anApplicationContext on demand for each named client using RibbonClientConfiguration. This contains (amongst other things) an ILoadBalancer, a RestClient, and a ServerListFilter.

在Ribbon一個核心概念是命名的客戶端.每個負載 平衡器是共同元件的集合的一部分,通過遠端伺服器聯絡, 你把它作為應用程式開發者(例如,使用 @FeignClient註解)的名稱,Spring Cloud建立一個新的整體使用RibbonClientConfiguration為每一個客戶端命名的 ApplicationContext,這包含(除其他事項外)的ILoadBalancer,一個RestClient 實現和ServerListFilter

自定義Ribbon客戶端(Customizing the Ribbon Client)

You can configure some bits of a Ribbon client using external properties in <client>.ribbon.*, which is no different than using the Netflix APIs natively, except that you can use Spring Boot configuration files. The native options can be inspected as static fields in CommonClientConfigKey (part of ribbon-core).

你可以配置Ribbon客戶端擴充套件屬性 <client>.ribbon.*,它只不過是利用了不同的原生Netflix APIS, 但你可以使用 Spring Boot 配置檔案, 原生選項檢查的靜態屬性在 CommonClientConfigKey(部分為ribbon-core)

Spring Cloud also lets you take full control of the client by declaring additional configuration (on top of theRibbonClientConfiguration) using @RibbonClient. Example:

Spring clound 使用額外的配置(RibbonClientConfiguration)可以讓你充分控制客戶端, 使用@RibbonClient. 例子:

@Configuration
@RibbonClient(name = "foo", configuration = FooConfiguration.class)
public class TestConfiguration {
}

In this case the client is composed from the components already in RibbonClientConfiguration together with any inFooConfiguration (where the latter generally will override the former).

在這種情況下客戶端元件由 RibbonClientConfiguration 和一些 FooConfiguration組成 (通常後者會覆蓋前者)

The FooConfiguration has to be @Configuration but take care that it is not in a @ComponentScan for the main application context, otherwise it will be shared by all the @RibbonClients. If you use@ComponentScan (or @SpringBootApplication) you need to take steps to avoid it being included (for instance put it in a separate, non-overlapping package, or specify the packages to scan explicitly in the @ComponentScan).
FooConfiguration 必須有 @Configuration,而不是由主應用程式@ComponentScan收集,其他情況下會被@RibbonClients共享,如果你使用@ComponentScan@SpringBootApplication,那麼你應放入單獨的,非同名的包下或明確@ComponentScan掃描的指定包。

Spring Cloud Netflix provides the following beans by default for ribbon (BeanType beanName: ClassName):

Spring Cloud Netflix ribbon預設提供了以下beans (BeanType beanName: ClassName):

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl

  • IRule ribbonRule: ZoneAvoidanceRule

  • IPing ribbonPing: NoOpPing

  • ServerList<Server> ribbonServerList: ConfigurationBasedServerList

  • ServerListFilter<Server> ribbonServerListFilter: ZonePreferenceServerListFilter

  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer

Creating a bean of one of those type and placing it in a @RibbonClient configuration (such as FooConfigurationabove) allows you to override each one of the beans described. Example:

建立一個bean來自其中一個型別,並把它放在一個@RibbonClient的配置(比如上面的FooConfiguration ), 允許你覆蓋一個描述的Bean. 例:

@Configuration
public class FooConfiguration {
    @Bean
    public IPing ribbonPing(IClientConfig config) {
        return new PingUrl();
    }
}

This replaces the NoOpPing with PingUrl.

這裡用PingUrl替換NoOpPing.

在Eureka中使用Ribbon(Using Ribbon with Eureka)

When Eureka is used in conjunction with Ribbon the ribbonServerList is overridden with an extension ofDiscoveryEnabledNIWSServerList which populates the list of servers from Eureka. It also replaces the IPing interface with NIWSDiscoveryPing which delegates to Eureka to determine if a server is up. The ServerList that is installed by default is a DomainExtractingServerList and the purpose of this is to make physical metadata available to the load balancer without using AWS AMI metadata (which is what Netflix relies on). By default the server list will be constructed with "zone" information as provided in the instance metadata (so on the remote clients seteureka.instance.metadataMap.zone), and if that is missing it can use the domain name from the server hostname as a proxy for zone (if the flag approximateZoneFromHostname is set). Once the zone information is available it can be used in a ServerListFilter. By default it will be used to locate a server in the same zone as the client because the default is a ZonePreferenceServerListFilter. The zone of the client is determined the same way as the remote instances by default, i.e. via eureka.instance.metadataMap.zone.

當 Eureka 和 Ribbon 的 ribbonServerList 一起使用來自Eureka中被覆蓋且擴充套件的 DiscoveryEnabledNIWSServerList伺服器列表,它用IPing介面 和 NIWSDiscoveryPing 委託給Eureka來確保伺服器是否啟動,安裝在ServerList預設值為DiscoveryEnabledNIWSServerList 這樣的目的是使用物理元資料提供給負載均衡器,而無需使用AWS AMI元資料(這是Netflix的依賴),預設情況下,伺服器列表將由“區域”中提供的資訊例項元資料(遠端客戶端設定eureka.instance.metadataMap.zone),如果缺少它可以使用從伺服器主機名作為區域代理的域名(如標誌approximateZoneFromHostname設定)。一旦該區域資訊可用它可以在一個ServerListFilter使用。預設情況下,將被使用在同一區域定位伺服器作為客戶端,因為預設是ZonePreferenceServerListFilter。的區域客戶被確定相同的方式由預設遠端例項即通過eureka.instance.metadataMap.zone

The orthodox "archaius" way to set the client zone is via a configuration property called "@zone", and Spring Cloud will use that in preference to all other settings if it is available (note that the key will have to be quoted in YAML configuration).

NOTE:規範的 "archaius" 方式去設定客戶端區,可以使用配置屬性"@zone", Spring Cloud 將優先於所有的其他設定(注意:該重點將在 YAML 配置被引用)

If there is no other source of zone data then a guess is made based on the client configuration (as opposed to the instance configuration). We take eureka.client.availabilityZones, which is a map from region name to a list of zones, and pull out the first zone for the instance’s own region (i.e. theeureka.client.region, which defaults to "us-east-1" for comatibility with native Netflix).

NOTE:如果沒有其他來源的區域資料則由基於客戶機的配置(而不是例項配置).我們把 eureka.client.availabilityZones, 這是一個從區域名稱對映到區域的列表,並拿出第一個區為例項自己的區域(即eureka.client.region, 預設為"us-east-1" 與 原生的Netflix comatibility)

示例: 沒有Eureka時如何使用Ribbon(Example: How to Use Ribbon Without Eureka)

Eureka is a convenient way to abstract the discovery of remote servers so you don’t have to hard code their URLs in clients, but if you prefer not to use it, Ribbon and Feign are still quite amenable. Suppose you have declared a@RibbonClient for "stores", and Eureka is not in use (and not even on the classpath). The Ribbon client defaults to a configured server list, and you can supply the configuration like this

Eureka 是一種很方便的抽象方式去發現遠端伺服器,所以你不需要硬編碼他們的客戶端URL,但如果你不喜歡使用它,Ribbon 和 Feign 仍然經得起檢驗,假設你已經聲明瞭 @RibbonClient 為 "stores", 與 Eureka 是不使用(甚至不能在類路徑). Ribbon 客戶端預設配置的伺服器列,並且可以提供這樣的配置

application.yml

stores:
  ribbon:
    listOfServers: example.com,google.com

示例:禁用Eureka使用Ribbon(Example: Disable Eureka use in Ribbon)

Setting the property ribbon.eureka.enabled = false will explicitly disable the use of Eureka in Ribbon.

設定屬性ribbon.eureka.enabled = false, 使用Ribbon時禁用Eureka

application.yml

ribbon:
  eureka:
   enabled: false

直接使用Ribbon的API(Using the Ribbon API Directly)

You can also use the LoadBalancerClient directly. Example:

你也可以直接使用 LoadBalancerClient,例子:

            
           

相關推薦

Spring CloudSpring Cloud中文手冊

歡迎關注公眾號: ----------------------------------------------正文---------------------------------------------------- Spring Cloud Netflix

spring cloudspring cloud 使用feign呼叫,1.fallback熔斷器不起作用,2.啟動報錯Caused by: java.lang.ClassNotFoundException: com.netflix.hystrix.contrib.javanica.aop.asp

1.首先使用feign呼叫,需要配置熔斷器 2.配置熔斷器需要將熔斷器注入Bean,被spring可以掃描到 3.熔斷器類需要實現feignClient介面 4.hystrix的jar需要被maven引用,並且在classpath下 5.注意,feignClient上儘量不要使用@RequestMap

spring cloudspring cloud Sleuth 和Zipkin 進行分散式鏈路跟蹤

spring cloud 分散式微服務架構下,所有請求都去找閘道器,對外返回也是統一的結果,或者成功,或者失敗。 但是如果失敗,那分散式系統之間的服務呼叫可能非常複雜,那麼要定位到發生錯誤的具體位置,就是一個比較麻煩的問題。 所以定位故障點,就引入了spring cloud Sleuth【Sleuth是獵

備忘Spring Cloud微服務架構視訊

01 Spring Cloud介紹與環境搭建 02 Spring Boot使用 03 執行第一個Eureka程式 04 搭建Eureka叢集 05 客戶端健康檢測與常用配置 06 第一個Ribbon程式 07 Ribbon負載均衡機制 08 Spring中使用Ribbon 0

spring-cloudspring-cloud-從入門到高可用-中

本篇帶大家從入門走向高可用,從屌絲走向高富帥... 1.先搭一個最簡單的專案,找點自信: 最簡單的spring-cloud專案需要一個註冊中心和兩個微服務,其他元件後面引入,這裡先不提, 註冊中心eurka程式碼入下: 先看依賴: 其中spring-boot版本採用2

夯實Spring CloudSpring Cloud中的Eureka服務註冊與發現詳解

本文屬於【夯實Spring Cloud】系列文章,該系列旨在用通俗易懂的語言,帶大家瞭解和學習Spring Cloud技術,希望能給讀者帶來一些乾貨。系列目錄如下: 【夯實Spring Cloud】Dubbo沉睡5年,Spring Cloud開始崛起! 【夯實Spring C

Spring Cloudspring boot搭建+swagger-ui

spring boot 搭建restful介面專案 spring cloud 系列 環境: jdk1.8、maven3.x 、IDEA 簡介 搭建專案 1、新建專案 新建完成專案 新建類

常用配置Spring框架web.xml通用配置

name star spring config ini param lis 框架 -name <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun

spring BootSpring中@Controller和@RestController之間的區別

處理 public 不同 esp 舉例 rest control tro adding spring Boot入手的第一天,看到例子中的@RestController ............. 相同點:都是用來表示Spring某個類的是否可以接收HTTP請求 不同點:@C

spring Bootspring boot獲取資源文件的三種方式兩種情況下

不用 ash 12c ica pla bsp foreach set 使用 首先聲明一點,springboot獲取資源文件,需要看是   1》從spring boot默認的application.properties資源文件中獲取   2》還是從自定義的資源文件中獲取

日常錯誤spring-boot配置文件讀取不到

無法 pan factory sdn 一個 pre nco span xxx 最近在用spring-boot做項目時,遇到自定義的配置文件無法讀取到的問題,通過在appcation.java類上定義@PropertySource(value = {"classpath:XX

spring boot框架學習8-幹貨spring boot的web開發(4)-自定義攔截器處理權限

凱哥spring boot spring boot框架 本章節主要內容:通過前面的學習,我們了解並快速完成了spring boot第一個應用。spring boot企業級框架,那麽spring boot怎麽讀取靜態資源?如js文件夾,css文件以及png/jpg圖片呢?怎麽自定義消息轉換器呢?怎麽自定

java學習spring mvc 公共dao的實現,定義基本的增刪改查

pri 代碼 部分 lec sse encoding del epo repos 接口類:    package com.blog.db.dao; import com.blog.util.Pagination; import java.util.Lis

spring mvcspring mvc接收單個參數

delete div 示例 public req TP 單個 class AR spring mvc接收單個參數 示例代碼: public AjaxResult<String> deleteList(@RequestParam(value = "uid") S

學習筆記Spring AOP註解使用總結

trace -a tid nat 修改 with this throwable pid Spring AOP基本概念 是一種動態編譯期增強性AOP的實現 與IOC進行整合,不是全面的切面框架 與動態代理相輔相成 有兩種實現:基於jdk動態代理、cglib Spring

圖文解析Spring瞭解一下啊,圖文解釋,一看就懂小老弟!

1.Spring簡介 什麼是Spring: spring產生於2003年,輕量級javase/ee一站式開源框架。 spring在三層架構的地位: 表示層:SpringMVC/struts2 業務邏輯層:Spring fra

nosql-redisspring整合redis

環境: MAVEN+SPRING+MYBATIS+MYSQL+REDIS 1 pom.xml檔案下載依賴: <dependency> <groupId>org.springframework.data</groupId> &

開源專案Spring Security三大許可權框架案例講解01—專案初始化

GitHub 前言 大致簡介專案主要逐步迭代講解Spring Security + Spring Social + Spring Security OAuth + REST服務開發,通過實際的案例開發來講解,專案註解詳細適合作為教程案例,同時對程式碼的演進還有重構

第一章Spring概述

1.1.1  Spring是什麼 Spring是一個開源的輕量級Java SE(Java 標準版本)/Java EE(Java 企業版本)開發應用框架,其目的是用於簡化企業級應用程式開發。應用程式是由一組相互協作的物件組成。而在傳統應用程式開發中,一個完整的應用是由一組相互

備忘spring boot 和netty 實現聊天工具 從開發到部署實戰

一: 課程概要 二: netty初識及BIO、NIO、AIO等執行緒模型 三: netty編寫簡單伺服器及channel詳解 四: netty與hbuilder開發websocket伺服器 五: H5與MUI構建移動端app 六: 資料庫設計及整合Springboot MyB