原文地址:http://blog.csdn.net/yp090416/article/details/78017552
springcloud微服務實戰:Eureka+Zuul+Ribbon+Hystrix+SpringConfig
相信現在已經有很多小伙伴已經或者准備使用springcloud微服務了,接下來為大家搭建一個微服務框架,后期可以自己進行擴展。會提供一個小案例: 服務提供者和服務消費者 ,消費者會調用提供者的服務,新建的項目都是用springboot,附源碼下載。
coding倉庫地址: coding地址 csdn下載地址: csdn下載地址
如果有問題請在下邊評論,或者200909980加群交流。
Eureka:服務發現
Hystrix:斷路器
Zuul:智能路由
Ribbon:客戶端負載均衡
Turbine:集群監控
Springcloud-config:遠程獲取配置文件
接下來,我們開始搭建項目,首先我們到spring為我們提供的一個網站快速搭建springboot項目,點擊訪問,我這里用的是gradle,如果各位客官喜歡用maven,好吧你可以到http://mvnrepository.com/查看對應的依賴,點我訪問。
一、搭建eureka-server服務springcloud-eureka-server
eureka-server作為服務發現的核心,第一個搭建,后面的服務都要注冊到eureka-server上,意思是告訴eureka-server自己的服務地址是啥。當然還可以用zookeeper或者springconsul。
- 1.修改build.gradle文件
如果是maven項目請對應的修改pom.xml
//加入阿里的私服倉庫地址
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
- 1
- 2
//加入依賴
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-eureka-server', version: '1.3.4.RELEASE'
//加入security,是因為訪問eureka-server需要用戶名和密碼訪問,為了安全
compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '1.5.6.RELEASE'
- 1
- 2
- 3
- 4
還有幾點需要修改的,大家對應圖片看看,就是springboot打包的時候會提示找不到主累。
- 2.修改 application.yml,建議用yml。
server:
port: 8761
eureka:
datacenter: trmap
environment: product
client:
healthcheck:
enabled: true
service-url:
defaultZone: http://root:booszy@localhost:8761/eureka
register-with-eureka: false #關閉自己作為客戶端注冊
fetch-registry: false
security:
basic:
enabled: true
user:
name: root #用戶名和密碼,等會訪問的時候,會要求你登錄,服務注冊的時候也需要帶着用戶名和密碼
password: booszy
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 3.修改程序的主類,建議修改類名,要加如eureka的 @EnableEurekaServer 注解,然后運行main方法。
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
http://localhost:8761/ 這個是eureka-server的頁面地址,到這里,說明eureka-server搭建好了,簡單吧,這一步一定要成功,否則后面的就不能繼續進行下去了,后邊基本類似。
二、搭建config-server服務springcloud-config-server
springcloud-config-server是用來將遠程git倉庫的配置文件動態拉下來,這樣配置文件就可以動態的維護了。
新建一個springboot項目,修改maven私服地址,並加入一下依賴。
- 1.修改build.gradle文件
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-eureka', version: '1.3.4.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-config-server', version: '1.3.2.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-actuator', version: '1.5.6.RELEASE'
//連接config-server也需要用戶名和密碼
compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '1.5.6.RELEASE'
- 1
- 2
- 3
- 4
- 5
- 2.修改application.yml文件
server:
port: 8500
eureka:
client:
service-url:
#注冊服務到eureka上,記住這里要加上eureka-server的用戶名和密碼
defaultZone: http://root:booszy@localhost:8761/eureka
instance:
prefer-ip-address: true
#可能比較長,復制的時候請寫在一行
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
appname: springcloud-config-server
spring:
application:
name: springcloud-config-server
cloud:
config:
server:
git:
#這是其他項目配置文件的git倉庫地址
uri: https://git.coding.net/yirenyishi/springcloud-config-profile
searchPaths: '{application}'
security:
basic:
enabled: true
user:
#這是config-server的用戶名和密碼
name: root
password: booszy
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 3.修改啟動類
修改啟動類,要加入這三個注解,因為要注冊到eureka-server上,所以需要@EnableEurekaClient這個注解
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
然后運行啟動springboot項目,等啟動成功后訪問eureka的頁面,會發現springcloud-config-server已經注冊到上面了,如果啟動報錯,請檢查錯誤信息。
三、搭建服務提供者服務springcloud-provider-config
編寫一個服務提供者,提供兩個接口,即獲取單個用戶的信息和獲取一個用戶列表。用到了spring-data-jpa 和 spring-webmvc ,當然你們公司用什么你還是繼續用什么。
-
- 注意 : 這里除了application.xml,還需要一個bootstrap.yml*
-
- 修改build.gradle文件
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
compile("com.alibaba:druid-spring-boot-starter:1.1.2")
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-eureka', version: '1.3.4.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-actuator', version: '1.5.6.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-config', version: '1.3.2.RELEASE'
compile group: 'org.springframework.session', name: 'spring-session-data-redis', version: '1.3.1.RELEASE'
runtime('mysql:mysql-connector-java')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 2.編寫配置文件bootstrap.yml
* 注意 : 這里除了application.xml,還需要一個bootstrap.yml
application.xml我是放到遠程倉庫地址的,大家可以直接到我的遠程倉庫,根據項目名(springcloud-provider-config)查詢。配置文件的倉庫地址:點擊訪問。
spring:
application:
name: springcloud-provider-config
cloud:
config:
#config-server的配置,不需要硬編碼config-server的地址,使用service-id去eureka-server獲取cong-server的地址
discovery:
enabled: true
service-id: springcloud-config-server
fail-fast: true
username: root
password: booszy
profile: dev
eureka:
client:
service-url:
defaultZone: http://root:booszy@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
appname: springcloud-provider-config
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 3.編寫代碼
編寫主類
@SpringBootApplication
@EnableEurekaClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
新建UserController, 考慮篇幅 UserService 和 UserRepository就不貼代碼了,想看的可以下載我的代碼。
@RequestMapping("user")
@RestController
public class UserController {
@Autowired
private UserService userService;
/** * @param id * @return */
@GetMapping("{id}")
public User getuser(@PathVariable String id) {
User user = null;
try {
System.out.println(id);
user = userService.find(id);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
/** * @return */
@GetMapping("list")
public List<User> users() {
try {
List<User> user = userService.findAll();
if (user != null && user.size() != 0) {
return user;
}
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
運行springboot項目,去eureka-server查看,有沒有注冊上。
我們的springcloud-provider-config已經注冊到eureka上了,訪問接口,成功。
四、搭建消費者服務springcloud-consumer-config-swagger
消費者要訪問服務提供者的服務,這里用的是通過RestTemplate請求resetful接口,使用ribbon做客戶端負載均衡,hystrix做錯誤處理,swagger生成接口文檔。
還是熟悉的配方,熟悉的味道,新建springboot項目,添加項目依賴。
- 1.修改build.gradle文件
compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-eureka', version: '1.3.4.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-actuator', version: '1.5.6.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-config', version: '1.3.2.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-hystrix', version: '1.3.4.RELEASE'
compile(
"io.springfox:springfox-swagger2:2.7.0",
"io.springfox:springfox-swagger-ui:2.7.0"
)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 2.修改bootstrap.yml文件
application.yml 在git倉庫,請前往git倉庫查看。
spring:
application:
name: springcloud-consumer-config
cloud:
config:
discovery:
enabled: true
service-id: springcloud-config-server
fail-fast: true
username: root
password: booszy
profile: dev
eureka:
client:
service-url:
defaultZone: http://root:booszy@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
appname: springcloud-consumer-config
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 3.編寫代碼
啟動類代碼
@RibbonClient 指定服務使用的負載均衡類型,name不指定服務則為所有的服務打開負載均衡,也可以在用yml中進行配置。
@EnableHystrix 是支持hystrix打開斷路器,在規定時間內失敗參數超過一定參數,就會打開斷路器,不會發起請求,而是直接進入到錯誤處理方法。
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "springcloud-provider-config", configuration = RibbonConfiguration.class)
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExtendRibbon.class)})
@EnableHystrix
public class ConsumerApplication {
@Autowired
private RestTemplateBuilder builder;
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return builder.build();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
新建UserController
ribbon一個坑,不能接受List類型,要使用數組接收。
@Api xxx 是swagger的注解
@HystrixCommand(fallbackMethod=”userFallbackMethod”)
如果請求失敗,會進入userFallbackMethod這個方法,userFallbackMethod這個方法要求參數和返回值與回調他的方法保持一致。
ribbon這個方法就是通過service-id獲取獲取服務實際的地址,這樣服務的地址就不用硬編碼了。
@Api("springcloud consumer user 控制器")
@RequestMapping("user")
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
/** * @param id * @return */
@ApiOperation(value = "根據用戶id查詢用戶信息", httpMethod = "GET", produces = "application/json")
@ApiResponse(code = 200, message = "success", response = User.class)
@GetMapping("{id}")
@HystrixCommand(fallbackMethod="userFallbackMethod")
public User getUser(@ApiParam(name = "id", required = true, value = "用戶Id") @PathVariable String id) {
return this.restTemplate.getForObject("http://springcloud-provider-config/user/" + id, User.class);
}
public User userFallbackMethod(String id){
return null;
}
/** * 這塊ribbon不支持復雜數據類型list,所以要用數組接受,然后轉list * @return */
@GetMapping("list")
@HystrixCommand(fallbackMethod = "userList")
public List<User> users(HttpServletRequest request) {
try {
User[] forObject = this.restTemplate.getForObject("http://springcloud-provider-config/user/list", User[].class);
List<User> users = Arrays.asList(forObject);
return users == null ? new ArrayList<User>() : users;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<User> userList(HttpServletRequest request) {
return null;
}
/** * 通過服務id獲取服務的地址 * @return */
@GetMapping("ribbon")
public String ribbon(){
ServiceInstance serviceInstance = loadBalancerClient.choose("springcloud-provider-config");
return serviceInstance.getUri().toString();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
運行springboot項目,先看有沒有注冊到eureka-server上。
注冊成功后,訪問接口,測試是否正確。
測試swagger-ui,訪問localhost:8200/swagger-ui.html
到這里消費者服務就算是完成了,后邊大家自己進行擴展。
五、用zuul做路由轉發和負載均衡
這些微服務都是隱藏在后端的,用戶是看不到,或者不是直接接觸,可以用nginx或者zuul進行路由轉發和負載均衡,zuul負載均衡默認用的是ribbon。
- 1.修改build.gradle文件
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-eureka', version: '1.3.4.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-zuul', version: '1.3.4.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-actuator', version: '1.5.6.RELEASE'
compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-config', version: '1.3.2.RELEASE'
- 1
- 2
- 3
- 4
- 2.修改bootstrap.yml
還是原來的配方,application.yml在git倉庫
spring:
application:
name: springcloud-zuul
cloud:
config:
discovery:
enabled: true
service-id: springcloud-config-server
fail-fast: true
username: root
password: booszy
profile: dev
eureka:
client:
service-url:
defaultZone: http://root:booszy@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
appname: springcloud-zuul
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 3.啟動類
@RefreshScope這個注解是當application.yml配置文件發生變化的時候,不需要手動的進行重啟,調用localhost:8400/refresh,就會加載新的配置文件,當然正在訪問的客戶並不影響還是使用舊的配置文件,因為不是重啟,后來的用戶會使用新的配置文件。注意這塊的刷新要用post請求。
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@RefreshScope
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
啟動springboot項目,訪問eureka-server
這時候,我們就要通過zuul訪問微服務了,而不是直接去訪問微服務。
應該訪問地址http://192.168.89.89:8400/springcloud-consumer-config/user/list,這塊你要換成你的zuul地址。
但是有些人就會說,這樣以后用戶請求會不會太長,比較反感,所以可以通過配置進行修改訪問地址。
zuul:
routes:
springcloud-consumer-config: /consumer/**
springcloud-provider-config: /provider/**
- 1
- 2
- 3
- 4
在application.yml中加入這樣一段配置,其實就是nginx中的反向代理,使用一下簡短的可以代理這個微服務。這個時候我們就可以這樣去訪問了http://192.168.89.89:8400/consumer/user/list,是不是簡短了很多