Spring Boot各模块作用

1、spring-boot
web容器整合,快速开发,上下文、外部配置、日志的统一管理

2、spring-boot-autoconfigure
自动配置,自动判断需要的jar包

3、spring-boot-actuator
生产环境管理,用rest方式给出多种接口:
mappings/autoconfig/configprops/beans
env/info/health/heapdump/metrics
loggers/logfile/dump/trace
shutdown/auditevents

4、spring-boot-starters
各种配置好的功能模块,用于快速拼装各种需要的功能

5、spring-boot-loader
用于加载jar包中的jar,可以实现单个jar/war的运行
注意:这种jar包放到jar包时,不要再次压缩

6、spring-boot-cli
快速开发groovy

7、spring-boot-devtools
方便调试,远程调试

Spring Cloud Sleuth入门

1、下载并运行zipkin
https://github.com/openzipkin/docker-zipkin

sudo ./docker-compose up

2、运行示例程序,并触发对应方法

spring-cloud-sleuth-sample-zipkin(需要Zipkin)
或者
spring-cloud-sleuth-sample-stream(需要RabbitMQ+Zipkin)

3、查看运行情况
http://localhost:9411

Spring Cloud Netflix入门(Feign)

Feign是一个很好用的REST通讯包,十分强大。

1、MyFeignClient

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import feign.hystrix.FallbackFactory;


import org.springframework.stereotype.Component;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(clients = {MyFeignClient.IServiceClient.class})
@RestController
public class MyFeignClient 
{
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	public static void main(String[] args)
	{
		new SpringApplicationBuilder(MyFeignClient.class).web(true).run(args);
	}
	
	@RequestMapping("/")
	public String hello() {
		return "It works";
	}
	
	@Autowired
	private IServiceClient aClient;
	
	@RequestMapping("/invokeC")
	public String invokeC() {
		return aClient.invokeA();
	}
	
	@RequestMapping("/invokeC/{clientName}")
    String invokeC(@PathVariable("clientName") String clientName)
    {
		if(aClient==null)
		{
			return "aClient is null";
		}
		else
		{
			//return aClient.invokeA(clientName);
			return aClient.invokeA();
		}
    }
	
	//primary = false
	@FeignClient(name="netflix-feign-server", configuration = MyFeignClientConfiguration.class, fallbackFactory=HystrixClientFallbackFactory.class)
	public interface IServiceClient {
	    @RequestMapping(method = RequestMethod.GET, value = "/invokeA")
	    String invokeA();

	    //@RequestMapping(method = RequestMethod.GET, value = "/invokeA/{clientName}", consumes = "application/json")
	    //String invokeA(@PathVariable("clientName") String clientName);
	}
	
	@Component
    public static class HystrixClientFallbackFactory implements FallbackFactory<IServiceClient>{
    	@Override
    	public IServiceClient create(final Throwable cause) {
    		return new IServiceClient() {
    			@Override
    		    public String invokeA()
    		    {
    				return "invokeA failed: "+cause.getMessage();
    		    }

    			//@Override
    			//public String invokeA(String clientName)
    		    //{
    			//	return "invokeA with clientName "+clientName+" failed: "+cause.getMessage();
    		    //}
    		};
    	}
    }
}

2、MyFeignClientConfiguration

package com.neohope.springcloud.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.Logger;
import feign.auth.BasicAuthRequestInterceptor;

@Configuration
public class MyFeignClientConfiguration {
	@Bean
	public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
		return new BasicAuthRequestInterceptor("user", "hystrix");
	}

	/*
	@Bean
	Logger.Level feignLoggerLevel() {
		return Logger.Level.FULL;
	}
	*/
}

3、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-feign-client</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-feign-client</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

4、application.properties

spring.application.name=feign-client
server.port=7002
security.user.name=user
security.user.password=hystrix
eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.preferSameZoneEureka=true
eureka.client.healthcheck.enabled=true
eureka.instance.metadataMap.zone = zone1
eureka.instance.statusPageUrlPath=${management.context-path}/info
eureka.instance.healthCheckUrlPath=${management.context-path}/health
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10
feign.hystrix.enabled=true
#feign.compression.request.enabled=true
#feign.compression.response.enabled=true
#feign.compression.request.enabled=true
#feign.compression.request.mime-types=text/xml,application/xml,application/json
#feign.compression.request.min-request-size=2048
#NONE,BASIC,HEADERS,FULL
logging.level.com.neohope.springcloud.test.MyFeignClient.IServiceClient=BASIC

Spring Cloud Netflix入门(Sidecar)

SideCar主要是用于将非JVM语言的服务,代理为Netflix服务

1、SideCarApp

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.sidecar.EnableSidecar;
import org.springframework.web.bind.annotation.RequestMapping;

//作用一、注册到eureka并提供服务健康状态
//其他语言的服务,首先服务封装为REST或JSON通信,并提供一个health路径,反馈服务是否正常
//sidecar会将这个服务注册到eureka
//其他服务,可以通过eureka查询并调用该服务

//作用二、从sidecar获取服务地址,并调用
//访问sidecar,获取服务地址  http://localhost:port/hosts/{serviceId}.
//分析返回结果,得到服务地址
//调用需要的服务
@EnableSidecar
public class SideCarApp 
{
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	@RequestMapping("/")
	public String hello() {
		return "It works";
	}
	
    public static void main( String[] args )
    {
    	new SpringApplicationBuilder(SideCarApp.class).web(true).run(args);
    }
}

2、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-sidecar-test</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-sidecar-test</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-sidecar</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

3、application.properties

spring.application.name=zuul-gateway-app
server.port=7001
security.user.name=user
security.user.password=hystrix

eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.preferSameZoneEureka=true
eureka.client.healthcheck.enabled=true
eureka.instance.metadataMap.zone = zone1
eureka.instance.statusPageUrlPath=${management.context-path}/info
eureka.instance.healthCheckUrlPath=${management.context-path}/health
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10

sidecar.port=9999
sidecar.health-uri=http://localhost:9999/health.json

Spring Cloud Netflix入门(Zuul)

Zuul就是一个API网关。

1、ZuulGatewayApp.java

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableEurekaClient
@RestController
@EnableZuulProxy
//@EnableZuulServer
public class ZuulGatewayApp 
{
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	public static void main(String[] args)
	{
		new SpringApplicationBuilder(ZuulGatewayApp.class).web(true).run(args);
	}
	
	@RequestMapping("/")
	public String hello() {
		return "It works";
	}
}

2、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-zuul-gateway</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-zuul-gateway</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-zuul</artifactId>
		</dependency>
		<dependency>
			<groupId>com.netflix.feign</groupId>
			<artifactId>feign-okhttp</artifactId>
			<version>8.18.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

3、application.properties

spring.application.name=zuul-gateway-app
server.port=7001
security.user.name=user
security.user.password=hystrix

eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.preferSameZoneEureka=true
eureka.client.healthcheck.enabled=true
eureka.instance.metadataMap.zone = zone1
eureka.instance.statusPageUrlPath=${management.context-path}/info
eureka.instance.healthCheckUrlPath=${management.context-path}/health
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10

zuul.host.maxTotalConnections=200
zuul.host.maxPerRouteConnections=20
#zuul.ignoredServices='*'
zuul.routes.netflix-feign-server.sensitiveHeaders
zuul.routes.netflix-feign-server.path=/invokeA/**
zuul.routes.netflix-feign-server.serviceId=netflix-feign-server
#zuul.routes.netflix-feign-server.url=
#zuul.ribbonIsolationStrategy=THREAD
#zuul.prefix=api
zuul.stripPrefix=false
#zuul.addProxyHeaders=false
#zuul.ignoredHeaders=
#zuul.forceOriginalQueryStringEncoding=true
#zuul.SendResponseFilter.post.disable=true.

#ribbon.eureka.enabled=false
#ribbon.restclient.enabled=true
#ribbon.okhttp.enabled=true
#ribbon.ConnectTimeout=3000
#ribbon.ReadTimeout=60000
#users.ribbon.listOfServers=172.16.172.63

#hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=60000

Spring Cloud Netflix入门(Turbine)

Turbine是一个日志收集器,用于聚合Hystrix中的日志。

1、TurbineServer

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.stream.EnableTurbineStream;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
@EnableCircuitBreaker
@EnableEurekaServer
@EnableHystrixDashboard
@EnableTurbineStream
public class TurbineServer 
{
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	public static void main(String[] args) {
        new SpringApplicationBuilder(TurbineServer.class).web(true).run(args);
    }
}

2、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-turbine-server</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-turbine-server</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-turbine-stream</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-stream-kafka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

3、application.properties

spring.application.name=turbine-server
server.port=7000
security.user.name=user
security.user.password=hystrix
eureka.instance.leaseRenewalIntervalInSeconds=5
eureka.instance.metadataMap.zone = zone1
eureka.server.enable-self-preservation=false
eureka.server.eviction-interval-timer-in-ms=5000
eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.preferSameZoneEureka=true
manager.port=7000
turbine.stream.port=8989

4、TurbineClient

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@SpringBootApplication
@EnableEurekaClient
@RestController
@EnableCircuitBreaker
public class TurbineClient 
{
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	@RequestMapping("/")
	public String hello() {
		return "It works";
	}
	
	@RequestMapping("/invokeA")
	@HystrixCommand(fallbackMethod = "invoekD")
	public String invokeA() {
		if(Math.random()>0.2)
		{
			throw new RuntimeException("Hystrix Test A thrown");
		}
		else
		{
			return "Hystrix Test A";
		}
	}
	
	@RequestMapping("/invokeB")
	@HystrixCommand(fallbackMethod = "invoekD")
	public String invokeB() {
		if(Math.random()>0.5)
		{
			throw new RuntimeException("Hystrix Test A thrown");
		}
		else
		{
			return "Hystrix Test A";
		}
	}
	
	@RequestMapping("/invokeD")
	public String invoekD() {
		return "Hystrix Test D";
	}
	
	public static void main(String[] args)
	{
		new SpringApplicationBuilder(TurbineClient.class).web(true).run(args);
	}
}

5、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-turbine-client</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-turbine-client</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-hystrix-stream</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-stream-kafka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

6、application.properties

spring.application.name=turbine-client
server.port=7001
security.user.name=user
security.user.password=hystrix
eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.preferSameZoneEureka=true
eureka.client.healthcheck.enabled=true
eureka.instance.metadataMap.zone = zone1
eureka.instance.statusPageUrlPath=${management.context-path}/info
eureka.instance.healthCheckUrlPath=${management.context-path}/health
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10
#eureka.instance.metadata-map.management.port=7001
#management.port=7002
turbine.aggregator.clusterConfig=default
turbine.appConfig=turbine-client
turbine.stream.port=8989

7、在以下地址可以访问
http://172.16.172.63:7001/hystrix.stream
http://user:hystrix@172.16.172.63:7002/turbine.stream

Spring Cloud Netflix入门(Hystrix)

HyStrix主要负责日志收集。同时是一个很棒的断路器。

1、HystrixServer

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
@EnableCircuitBreaker
@EnableEurekaServer
@EnableHystrixDashboard
@EnableTurbine
public class HystrixServer 
{
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	public static void main(String[] args) {
        new SpringApplicationBuilder(HystrixServer.class).web(true).run(args);
    }
}

2、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-hystrix-server</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-hystrix-server</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-turbine</artifactId>
		</dependency>
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

3、application.properties

spring.application.name=hystrix-server
server.port=7000
security.user.name=user
security.user.password=hystrix
eureka.instance.leaseRenewalIntervalInSeconds=5
eureka.instance.metadataMap.zone = zone1
eureka.server.enable-self-preservation=false
eureka.server.eviction-interval-timer-in-ms=5000
eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.preferSameZoneEureka=true
#turbine.instanceUrlSuffix=/hystrix.stream
turbine.aggregator.clusterConfig=default
turbine.appConfig=hystrix-client01,hystrix-client02
#eureka.instance.metadata-map.management.port=${management.port:7000}
#management.port=7000

4、HystrixClient01

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@SpringBootApplication
@EnableEurekaClient
@RestController
@EnableCircuitBreaker
public class HystrixClient01 {
	
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	@RequestMapping("/")
	public String hello() {
		return "It works";
	}
	
	@RequestMapping("/invokeA")
	//@HystrixCommand(fallbackMethod = "invoekD", 
	//commandProperties = {@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")})
	@HystrixCommand(fallbackMethod = "invoekD")
	public String invokeA() {
		if(Math.random()>0.2)
		{
			throw new RuntimeException("Hystrix Test A thrown");
		}
		else
		{
			return "Hystrix Test A";
		}
	}
	
	@RequestMapping("/invokeB")
	@HystrixCommand(fallbackMethod = "invoekB")
	public String invokeB() {
		if(Math.random()>0.5)
		{
			throw new RuntimeException("Hystrix Test B thrown");
		}
		else
		{
			return "Hystrix Test B";
		}
	}
	
	@RequestMapping("/invokeD")
	public String invoekD() {
		return "Hystrix Test D";
	}
	
	public static void main(String[] args)
	{
		new SpringApplicationBuilder(HystrixClient01.class).web(true).run(args);
	}
}

5、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-hystrix-client01</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-hystrix-client01</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

6、application.properties

spring.application.name=hystrix-client01
server.port=7001
security.user.name=user
security.user.password=hystrix
eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.preferSameZoneEureka=true
eureka.client.healthcheck.enabled=true
eureka.instance.metadataMap.zone = zone1
eureka.instance.statusPageUrlPath=${management.context-path}/info
eureka.instance.healthCheckUrlPath=${management.context-path}/health
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10

7、HystrixClient02

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
//import org.springframework.cloud.netflix.turbine.EnableTurbine;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@SpringBootApplication
@EnableEurekaClient
@RestController
@EnableCircuitBreaker
//@EnableTurbine
public class HystrixClient02
{
	@Value("${spring.application.name}")
	private String appName;
	
	@RequestMapping("/appName")
	public String appName() {
		return appName;
	}
	
	@RequestMapping("/")
	public String hello() {
		return "It works";
	}
	
	@RequestMapping("/invokeA")
	@HystrixCommand(fallbackMethod = "invoekD")
	public String invokeA() {
		if(Math.random()>0.2)
		{
			throw new RuntimeException("Hystrix Test A thrown");
		}
		else
		{
			return "Hystrix Test A";
		}
	}
	
	@RequestMapping("/invokeB")
	@HystrixCommand(fallbackMethod = "invoekB")
	public String invokeB() {
		if(Math.random()>0.5)
		{
			throw new RuntimeException("Hystrix Test B thrown");
		}
		else
		{
			return "Hystrix Test A";
		}
	}
	
	@RequestMapping("/invokeD")
	public String invoekD() {
		return "Hystrix Test D";
	}
	
	public static void main(String[] args)
	{
		new SpringApplicationBuilder(HystrixClient02.class).web(true).run(args);
	}
}

8、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-hystrix-client02</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-hystrix-client02</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
		<!--dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-turbine</artifactId>
		</dependency-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>com.netflix.hystrix</groupId>
			<artifactId>hystrix-javanica</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

9、application.properties

spring.application.name=hystrix-client02
server.port=7002
security.user.name=user
security.user.password=hystrix
eureka.client.serviceUrl.defaultZone=http://user:hystrix@localhost:7000/eureka/
eureka.client.preferSameZoneEureka=true
eureka.client.healthcheck.enabled=true
eureka.instance.metadataMap.zone = zone1
eureka.instance.statusPageUrlPath=${management.context-path}/info
eureka.instance.healthCheckUrlPath=${management.context-path}/health
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10


10、可以在下面的地址,查看日志输出
http://172.16.172.63:7001/hystrix.stream

Spring Cloud Netflix入门(Eureka)

Eureka主要负责服务注册及服务发现,但同时带有负载均衡的作用。

1、AppEurekaServer

package com.neohope.springcloud.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaServer
public class AppEurekaServer 
{
	@RequestMapping("/appName")
	public String appName() {
		return System.getenv("spring.application.name");
	}
	
	public static void main(String[] args) {
		SpringApplication.run(AppEurekaServer.class, args);
		//new SpringApplicationBuilder(AppEurekaServer.class).web(true).run(args);
	}
}

2、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>


	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
		<!--groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-netflix</artifactId> 
			<version>1.3.0.M1</version> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> 
			<version>1.4.4.RELEASE</version -->
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-eureka-server</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-eureka-server</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<!--dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-zuul</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-ribbon</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-turbine-stream</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-turbine-amqp</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-turbine</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-spectator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-atlas</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-archaius</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-turbine-stream</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-turbine</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-spectator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-hystrix-stream</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-hystrix-amqp</artifactId>
		</dependency-->
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

3、application.properties

spring.application.name=eureka-server
server.port=7000
security.user.name=user
security.user.password=eureka
eureka.instance.leaseRenewalIntervalInSeconds=5
eureka.instance.metadataMap.zone = zone1
eureka.server.enable-self-preservation=false
eureka.server.eviction-interval-timer-in-ms=5000
eureka.client.serviceUrl.defaultZone=http://user:eureka@localhost:7000/eureka/
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false
eureka.client.preferSameZoneEureka = true

4、AppEurekaClient

package com.neohope.springcloud.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
//@EnableDiscoveryClient
@RestController
public class AppEurekaClient {
	
	//@Value("${spring.application.name}")
	//private String appName;
	
	@Autowired
	private EurekaClient discoveryClient;

	@RequestMapping("/serviceUrl")
	public String serviceUrl() {
	    //InstanceInfo instance = discoveryClient.getNextServerFromEureka("eureka-client", false);
	    //return instance.getHomePageUrl();
		return System.getenv("spring.application.name");
	}
	
	@RequestMapping("/")
	public String home() {
		return "It works!";
	}

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

5、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<artifactId>app-starters-build</artifactId>
		<version>1.1.3.M1</version>
		<!--groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> 
			<version>1.4.4.RELEASE</version -->
	</parent>

	<groupId>com.neohope.springcloud.test</groupId>
	<artifactId>netflix-eureka-client</artifactId>
	<version>1.0.0</version>
	<packaging>jar</packaging>

	<name>netflix-eureka-client</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
			<version>1.3.0.M1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

6、application.properties

spring.application.name=eureka-client
server.port=7001
security.user.name=user
security.user.password=eureka
eureka.client.serviceUrl.defaultZone=http://user:eureka@localhost:7000/eureka/
eureka.client.preferSameZoneEureka=true
eureka.client.healthcheck.enabled=true
eureka.instance.metadataMap.zone = zone1
eureka.instance.statusPageUrlPath=${management.context-path}/info
eureka.instance.healthCheckUrlPath=${management.context-path}/health
eureka.instance.lease-renewal-interval-in-seconds=5
eureka.instance.lease-expiration-duration-in-seconds=10

Spring Cloud Consul入门

1、启动consul

consul agent -dev
#consul agent -dev -config-dir=/etc/consul.d
#consul agent -data-dir=/tmp/consul -node=agent02 -bind=172.16.172.62 -config-dir=/etc/consul.d
#consul agent -server -bootstrap-expect=1 -data-dir=/tmp/consul -node=agent01 -bind=172.16.172.63 -config-dir=/etc/consul.d
#-bootstrap-expect=1	     等待一个节点加入
#-data-dir=/tmp/consu	     缓存路径
#-bind=172.20.20.10	     绑定ip地址
#-config-dir=/etc/consul.d   配置文件路径

==> Starting Consul agent...
==> Starting Consul agent RPC...
==> Consul agent running!
           Version: 'v0.7.5'
           Node ID: 'f82c6b1c-43b5-4423-af1d-343429555bbe'
         Node name: 'hiup03'
        Datacenter: 'dc1'
            Server: true (bootstrap: false)
       Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600, RPC: 8400)
      Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
    Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
             Atlas: <disabled>

==> Log data will now stream in as it occurs:

    2017/02/27 10:50:13 [DEBUG] Using unique ID "f82c6b1c-43b5-4423-af1d-343429555bbe" from host as node ID
    2017/02/27 10:50:13 [INFO] raft: Initial configuration (index=1): [{Suffrage:Voter ID:127.0.0.1:8300 Address:127.0.0.1:8300}]
    2017/02/27 10:50:13 [INFO] serf: EventMemberJoin: hiup03 127.0.0.1
    2017/02/27 10:50:13 [INFO] serf: EventMemberJoin: hiup03.dc1 127.0.0.1
    2017/02/27 10:50:13 [INFO] raft: Node at 127.0.0.1:8300 [Follower] entering Follower state (Leader: "")
    2017/02/27 10:50:13 [INFO] consul: Adding LAN server hiup03 (Addr: tcp/127.0.0.1:8300) (DC: dc1)
    2017/02/27 10:50:13 [INFO] consul: Adding WAN server hiup03.dc1 (Addr: tcp/127.0.0.1:8300) (DC: dc1)

    2017/02/27 10:50:19 [WARN] raft: Heartbeat timeout from "" reached, starting election
    2017/02/27 10:50:19 [INFO] raft: Node at 127.0.0.1:8300 [Candidate] entering Candidate state in term 2
    2017/02/27 10:50:19 [DEBUG] raft: Votes needed: 1
    2017/02/27 10:50:19 [DEBUG] raft: Vote granted from 127.0.0.1:8300 in term 2. Tally: 1
    2017/02/27 10:50:19 [INFO] raft: Election won. Tally: 1
    2017/02/27 10:50:19 [INFO] raft: Node at 127.0.0.1:8300 [Leader] entering Leader state
    2017/02/27 10:50:19 [INFO] consul: cluster leadership acquired
    2017/02/27 10:50:19 [DEBUG] consul: reset tombstone GC to index 3
    2017/02/27 10:50:19 [INFO] consul: New leader elected: hiup03
    2017/02/27 10:50:19 [INFO] consul: member 'hiup03' joined, marking health alive
    2017/02/27 10:50:19 [INFO] agent: Synced service 'consul'
    2017/02/27 10:50:19 [DEBUG] agent: Node info in sync
    2017/02/27 10:51:37 [INFO] agent.rpc: Accepted client: 127.0.0.1:39792
    2017/02/27 10:52:07 [DEBUG] agent: Service 'consul' in sync
    2017/02/27 10:52:07 [DEBUG] agent: Node info in sync
    2017/02/27 10:52:47 [DEBUG] http: Request GET /v1/catalog/nodes (218.436μs) from=127.0.0.1:33428

2、带管理界面的启动方式

consul agent -ui  -data-dir /tmp/consul-ui -bind=172.16.172.63
consul agent -ui -client 0.0.0.0 -data-dir=/tmp/consul -node=agent02 -bind=172.16.172.62 -config-dir=/etc/consul.d
#访问http://172.16.172.63:8500/ui/#/dc1/services

3、加入主节点consul

consul join 172.16.172.63
Successfully joined cluster by contacting 1 nodes

4、检查健康状况

curl http://172.16.172.63:8080/health
{"description":"Spring Cloud Consul Discovery Client","status":"UP"}

5、负载均衡相关

curl http://172.16.172.63:8080/choose
http://hiup03:8080

curl http://172.16.172.63:8080/instances
[{"serviceId":"testConsulApp","host":"hiup03","port":8080,"secure":false,"metadata":{},"uri":"http://hiup03:8080"}]

6、服务描述

curl http://172.16.172.63:8080/
{"serviceId":"testConsulApp","server":{"host":"hiup03","port":8080,"id":"hiup03:8080","zone":"UNKNOWN","readyToServe":true,"metaInfo":
{"serverGroup":null,"serviceIdForDiscovery":null,"instanceId":"testConsulApp-8080","appName":"testConsulApp"},"metadata":{},"healthService":{"node":
{"node":"agent01","address":"172.16.172.63"},"service":{"id":"testConsulApp-8080","service":"testConsulApp","tags":
[],"address":"hiup03","port":8080},"checks":[{"node":"agent01","checkId":"serfHealth","name":"Serf Health 
Status","status":"PASSING","notes":"","output":"Agent alive and reachable","serviceId":"","serviceName":""},
{"node":"agent01","checkId":"service:testConsulApp-8080","name":"Service 'testConsulApp' check","status":"PASSING","notes":"","output":"HTTP GET 
http://hiup03:8080/health: 200  Output: {\"description\":\"Spring Cloud Consul Discovery Client\",\"status\":\"UP\"}","serviceId":"testConsulApp-
8080","serviceName":"testConsulApp"}]},"passingChecks":true,"alive":true,"hostPort":"hiup03:8080"},"secure":false,"metadata":
{},"uri":"http://hiup03:8080","host":"hiup03","port":8080}

curl http://172.16.172.63:8080/me
{"serviceId":"testConsulApp-8080","host":"hiup03","port":8080,"secure":false,"metadata":{},"uri":"http://hiup03:8080"}

curl http://172.16.172.63:8080/rest
{"serviceId":"testConsulApp-8080","host":"hiup03","port":8080,"secure":false,"metadata":{},"uri":"http://hiup03:8080"}

curl http://172.16.172.63:8080/myenv
{"timestamp":1488183397275,"status":400,"error":"Bad 
Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required String parameter 'prop' is not present","path":"/myenv"}

curl http://172.16.172.63:8080/prop
default value

curl http://172.16.172.63:8080/feign
http://hiup03:8080

7、查看成员

consul members
Node     Address             Status  Type    Build  Protocol  DC
agent01  172.16.172.63:8301  alive   server  0.7.5  2         dc1
agent02  172.16.172.62:8301  alive   client  0.7.5  2         dc1

8、查看节点、域名及服务

curl http://localhost:8500/v1/catalog/nodes
curl http://localhost:8500/v1/catalog/service/hello
curl 'http://localhost:8500/v1/health/service/hello?passing'
curl http://localhost:8500/v1/health/state/critical
dig @localhost -p 8600 hiup03
dig @localhost -p 8600 hello.service.consul
dig @localhost -p 8600 hello.service.consul SRV
dig @localhost -p 8600 rails.hello.service.consul 
dig @localhost -p 8600 rails.hello.service.consul SRV
dig @127.0.0.1 -p 8600 hello.service.consul

dig @127.0.0.1 -p 8600 agent02.node.consul
; <<>> DiG 9.10.3-P4-Ubuntu <<>> @127.0.0.1 -p 8600 agent02.node.consul
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 61862
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;agent02.node.consul.           IN      A

;; ANSWER SECTION:
agent02.node.consul.    0       IN      A       172.16.172.62

;; Query time: 0 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: Mon Feb 27 11:44:25 CST 2017
;; MSG SIZE  rcvd: 53

9、重新加载服务

consul reload

10、键值数据库

consul kv put hiup/config/msg "read to go"
consul kv put -flags=15 hiup/config/msg_max_length 128

consul kv get hiup/config/msg
consul kv get -detailed  hiup/config/msg

consul kv get -recurse
consul kv delete hiup/config/msg
consul kv delete -recurse hiup

11、键值数据库并发处理

consul kv get -detailed  hiup/config/msg
CreateIndex      1094
Flags            0
Key              hiup/config/msg
LockIndex        0
ModifyIndex      1094
Session          -
Value            read to go

consul kv put -cas -modify-index=1093 hiup/config/msg "msg1093"
consul kv put -cas -modify-index=1094 hiup/config/msg "msg1094"