在此分享下本人最近搭建的一個springcloud微服務項目,包括注冊中心、配置中心、熔斷器、turbine熔斷器集中監控中心、fegin、前後端負載均衡、swagger2、網關、bus動态修改配置等等。項目隻是初步搭建,之後還會加入各種好玩的技術,會不定期更新,感興趣的可下載下傳進行研究交流,微服務的明天會更好。
github
arthur https://github.com/ArthurFamily/arthur.git
config https://github.com/ArthurFamily/config-center.git
碼雲
https://git.oschina.net/ArthurFamily/arthur.git
https://git.oschina.net/ArthurFamily/config-center.git
(注:配置檔案通過git項目讀取,放到一個項目中讀取超過5分鐘才會有響應,經測試不是網絡原因,配置檔案單獨放置一個項目沒有問題。)
<modules>
<!-- 注冊中心與配置中心使用jhipster2.6.0 -->
<module>arthur-eureka</module>
<!-- 配置中心 -->
<module>arthur-config-center</module>
<!-- 集中監控斷路器儀表盤 -->
<module>arthur-monitor-turbine</module>
<!-- zuul網關 -->
<module>arthur-gateway</module>
<!-- 背景管理之服務網管理 -->
<module>arthur-manage-serviceWeb</module>
<!-- 注冊流程 -->
<module>arthur-manage-registrationProcess</module>
</modules>
最後兩個子產品主要做子產品間通訊測試,沒有頁面,隻是簡單的連接配接了資料庫,頁面之後會增加。
注冊中心eureka主要使用的Jhipster的jhipster-registry-2.6.0版本,最新的版本3.1.0啟動異常,貌似是zuul的問題,故采用穩定版,頁面比原生的eureka頁面要美觀一些Jhipster抽空還會介紹,可以生成微服務項目,但是前端采用的angularjs,還在入門,故想內建bootstrap架構,是以子項目自己搭建,隻用它的注冊中心。如果需要搭建高可用叢集注冊中心,可部署多台eureka進行以來注冊,也就是通常說的服務端的負載均衡。
1.首先介紹下配置中心 arthur-config-center,需要引入spring-cloud-config-server
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>${springcloudconfig-version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
</dependencies>
加入EnableConfigServer注解
@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
public class ConfigCenter {
private static final Logger LOG = LoggerFactory.getLogger(ConfigCenter.class.getName());
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(ConfigCenter.class);
//DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
LOG.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://127.0.0.1:{} \n\t" +
"External: \thttp://{}:{} \n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name")+"("+env.getProperty("version")+")",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
env.getProperty("spring.profiles.active"));
}
}
進行注冊,這裡采用的高可用配置中心,可部署多台應用,然後依賴的項目跟進注冊中心的服務名去讀取各自的配置檔案
# 注冊中心
eureka:
client:
enabled: true
#注冊中心開啟健康檢查會重新整理上下文
healthcheck:
enabled: false
fetch-registry: true
register-with-eureka: true
instance-info-replication-interval-seconds: 10
registry-fetch-interval-seconds: 10
serviceUrl:
defaultZone: http://${eurekaCenter.username}:${eurekaCenter.pasword}@localhost:8761/eureka/
配置Git
#配置中心 GitHub配置
cloud:
config:
server:
git:
uri: https://github.com/ArthurFamily/config-center.git
search-paths: /config/dev
strict-host-key-checking: false
啟動後通路http://127.0.0.1:10002/arthur-manage-serviceWeb/dev,傳回配置檔案json, 這裡有一個對應規則,對應配置檔案中的{服務名-dev(profiles->active的名)},配置檔案中放置資料庫、redis等配置
2.微服務項目 arthur-manage-serviceWeb 包括mybatis分頁插件,自動配置資料源,與arthur-manage-registration 通過fegin進行接口調用,swagger2,ribbon的使用等。
<dependencies>
<!-- 自動配置,引入後,配置檔案裡必須配置,用到再引入故不在父級放置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${springboot-mybatis}</version>
<exclusions>
<exclusion>
<artifactId>spring-boot</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 資料庫分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>LATEST</version>
</dependency>
</dependencies>
公用的都在父級pom,部分如下fegin、hystrix、服務注冊發現的、讀取config的等
<!-- fegin 自帶斷路器-->
<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.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>${eureka-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>${springcloudconfig-version}</version>
<exclusions>
<exclusion>
<artifactId>spring-boot</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
mybatis-spring-boot-starter會自動讀取配置檔案中的資料源配置,無需我們自己去實作建立datasource、sqlsessionfactory等
spring:
application:
name: arthur-manage-serviceWeb
profiles:
active: dev
output:
ansi:
enabled: ALWAYS
jackson:
default-property-inclusion: non_null
cloud:
config:
discovery:
enabled: true
service-id: arthur-config-center
注意@MapperScan掃描mapper接口,原生的baseMapper不能被掃描到,故自己建立,掃描mapper配置檔案在application.yml中
# mybatis mapper 檔案
mybatis:
mapper-locations: classpath:mapper/**/*.xml
@EnableDiscoveryClient啟用注冊發現,@EnableFeignClients啟用fegin調用
@SpringBootApplication
@Import({WebMvcConfig.class})
@EnableScheduling
@ServletComponentScan
@RestController
@MapperScan(value = "**.mapper", markerInterface = BaseMapper.class)
@EnableDiscoveryClient
@EnableFeignClients // 調用服務
@EnableHystrix
public class ManageServiceWeb {
private static final Logger LOG = LoggerFactory.getLogger(ManageServiceWeb.class.getName());
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(ManageServiceWeb.class);
//DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
LOG.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://127.0.0.1:{} \n\t" +
"External: \thttp://{}:{} \n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name")+"("+env.getProperty("version")+")",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
env.getProperty("spring.profiles.active"));
}
分頁插件的使用
引入pom後在application.yml中增加配置
#分頁插件使用
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
在調用資料庫查詢之前增加
public List<Users> getUserList(int page, int pageSize) {
PageHelper.startPage(page, pageSize);
return usersMapper.getUserList();
}
隻對跟随在PageHelper之後的一條查詢有效,PageInfo中有自己需要的page,limit等
@ApiOperation("擷取使用者分頁清單")
@ApiImplicitParam(name = "offset", value = "目前頁數", required = true, dataType = "int", paramType = "query")
@RequestMapping(value = "/getUserList", method = RequestMethod.GET)
public Object getUserList(int offset) {
// 分頁通過request傳入參數
// PageHelper.offsetPage(offset, 1);
return new PageInfo(usersService.getUserList(offset,2));
}
下面再說一下fegin,自帶ribbon前端負載均衡,其實就是封裝了一下http請求,包括請求頭一些資料,自己也可以通過實作接口類去自定義,首先使用@EnableFeignClients啟用,然後建立接口,自己項目中就可以通過@Autowired直接注入使用了
@FeignClient(value = "arthur-manage-registrationProcess")
public interface RegistrationProcessFeignService {
@RequestMapping(value = "/test/{name}", method = RequestMethod.GET)
public String getServiceName(@PathVariable(value = "name") String name);
}
就會調用 arthur-manage-registrationProcess中的test方法,傳回想要的資訊
@RequestMapping(value = "/test/{name}", method = RequestMethod.GET)
public String getServiceName(@PathVariable(value = "name") String name) {
return "請求者:" + name + "請求arthur-manage-registrationProcess的test方法";
}
然後就是swagger2,可以幫助我們進行接口測試同時幫助我們維護API
公用的在父級
<!-- swagger支援 每個項目通過注冊中心的執行個體點選進入swagger頁面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
然後通過spring幫我們配置swagger,通過@EnableSwagger2啟用
/**
* 提供接口的服務需要引入此配置.
* eureka中home-page-url配置http://localhost:${server.port}/swagger-ui.html位址,通過注冊中心直接點選進入頁面
* Created by chenzhen on 2017/8/4.
*/
@Configuration
@EnableSwagger2 // 啟用Swagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {// 建立API基本資訊
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.cloud.arthur.controller"))// 掃描該包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {// 建立API的基本資訊,這些資訊會在Swagger UI中進行顯示
return new ApiInfoBuilder()
.title("ARTHUR-MANAGE-SERVICEWEB 接口 APIs")// API 标題
.description("服務端管理子產品對外暴露接口API")// API描述
.contact("[email protected]")// 聯系人
.version("1.0")// 版本号
.build();
}
}
然後要在自己的controller中對方法進行注釋,一定要指定method類型,否則所有種類的http方法都會建立一遍,也可用@[email protected]@PutMapping等注解,無需指定,這裡類型還要對應API注解中的paramType,如get方法對應query
@ApiIgnore
@RequestMapping("/hello")
public String hello(String name) {
return registrationProcessFeginService.getServiceName(name);
}
@ApiOperation("根據name擷取使用者資訊")
@ApiImplicitParam(name = "name", value = "使用者名稱", required = true, dataType = "String", paramType = "query")
@RequestMapping(value = "/getName", method = RequestMethod.GET)
public Users getName(String name) {
return usersService.getUserByName(name);
}
@ApiOperation("擷取使用者分頁清單")
@ApiImplicitParam(name = "offset", value = "目前頁數", required = true, dataType = "int", paramType = "query")
@RequestMapping(value = "/getUserList", method = RequestMethod.GET)
public Object getUserList(int offset) {
// 分頁通過request傳入參數
// PageHelper.offsetPage(offset, 1);
return new PageInfo(usersService.getUserList(offset,2));
}
通過http://localhost:${server.port}/swagger-ui.html通路頁面,這裡可以通過配置注冊中心的home-page-url,直接從注冊中心點選進入swagger頁面,項目多了維護起來也友善
# 注冊中心
eureka:
client:
enabled: true
#此處開啟健康檢查與高可用配置中心沖突,不可并存
healthcheck:
enabled: false
fetch-registry: true
register-with-eureka: true
instance-info-replication-interval-seconds: 10
registry-fetch-interval-seconds: 10
serviceUrl:
defaultZone: http://${eurekaCenter.username}:${eurekaCenter.pasword}@localhost:8761/eureka/
instance:
appname: ${spring.application.name}
instanceId: ${spring.application.name}:${spring.application.instance-id:${random.value}:${server.port}}
lease-renewal-interval-in-seconds: 5
lease-expiration-duration-in-seconds: 10
metadata-map:
zone: primary
profile: ${spring.profiles.active}
version: ${info.project.version}
#配置swagger位址通過注冊重點點選進入
home-page-url: http://localhost:${server.port}/swagger-ui.html
3.斷路器使用
<!-- 斷路器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
通過@EnableHystrix啟用熔斷器
然後需要熔斷的方法中自己實作一個方法,feign中直接實作自己的fegin接口就可以了,然後進行異常處理,fallback指向實作類。
@RequestMapping("/tests")
@HystrixCommand(fallbackMethod = "getNameFail")
public String getName() {
String a = null;
a.length();
return "success";
}
public String getNameFail() {
return "fail";
}
其實作在再加入@EnableHystrixDashboard,通過http://127.0.0.1:10004/hystrix通路頁面添加/hystrix/hystrix.stream就可以監控了,但是隻能監控自己,是以我們需要一個叢集監控,故此采用turbine
下面看一下arthur-monitor-turbine項目
<dependencies>
<!-- 監控斷路器總大盤 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-turbine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-turbine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
</dependencies>
通過@EnableTurbine啟用[email protected]啟用頁面大盤
@SpringBootApplication
@EnableDiscoveryClient
@EnableTurbine
@EnableHystrixDashboard
public class MonitorTurbine {
private static final Logger LOG = LoggerFactory.getLogger(MonitorTurbine.class.getName());
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(MonitorTurbine.class);
//DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
LOG.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://127.0.0.1:{} \n\t" +
"External: \thttp://{}:{} \n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name")+"("+env.getProperty("version")+")",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
env.getProperty("spring.profiles.active"));
}
}
集中配置檔案中配置需要監控的服務的名稱,這些服務都得啟用@EnableHystrix并配置fallback
turbine:
aggregator:
clusterConfig: default # 指定聚合哪些叢集,多個使用","分割,預設為default。可使用http://.../turbine.stream?cluster={clusterConfig之一}通路
appConfig: arthur-manage-registrationProcess,arthur-manage-serviceWeb # 配置Eureka中的serviceId清單,表明監控哪些服務
clusterNameExpression: new String("default")
# 1. clusterNameExpression指定叢集名稱,預設表達式appName;此時:turbine.aggregator.clusterConfig需要配置想要監控的應用名稱
# 2. 當clusterNameExpression: default時,turbine.aggregator.clusterConfig可以不寫,因為預設就是default
# 3. 當clusterNameExpression: metadata['cluster']時,假設想要監控的應用配置了eureka.instance.metadata-map.cluster: ABC,則需要配置,同時turbine.aggregator.clusterConfig: ABC
#前端負載配置
啟動後可看到監控的stream
通路http://127.0.0.1:10004/hystrix,并寫入turbine的stream http://127.0.0.1:10004/turbine.stream
通路熔斷器方法http://127.0.0.1:10003/tests,就可以看到大盤了
4.網關zuul的使用 arthur-gateway
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
</dependencies>
@EnableZuulProxy啟用網關代理@SpringCloudApplication包含@SpringBootApplication、@EnableDiscoveryClient、@EnableCircuitBreaker這仨注解
@SpringCloudApplication
@EnableZuulProxy
public class GateWay {
private static final Logger LOG = LoggerFactory.getLogger(GateWay.class.getName());
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(GateWay.class);
//DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
LOG.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://127.0.0.1:{} \n\t" +
"External: \thttp://{}:{} \n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name")+"("+env.getProperty("version")+")",
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
env.getProperty("spring.profiles.active"));
}
@Bean
public GatewayFilter gatewayFilter() {
return new GatewayFilter();
}
建立一個zuulfilter,接收請求的時候首先去校驗參數中是否包含我們配置的tocken,包含才繼續請求,加強安全認證
public class GatewayFilter extends ZuulFilter{
@Value("${spring.accessToken}")
private String accessToken;
@Override
public boolean shouldFilter() {
return true;
}
/*filterType:傳回一個字元串代表過濾器的類型,在zuul中定義了四種不同生命周期的過濾器類型,具體如下:
pre:可以在請求被路由之前調用
routing:在路由請求時候被調用
post:在routing和error過濾器之後被調用
error:處理請求時發生錯誤時被調用
filterOrder:通過int值來定義過濾器的執行順序
shouldFilter:傳回一個boolean類型來判斷該過濾器是否要執行,是以通過此函數可實作過濾器的開關。在上例中,我們直接傳回true,是以該過濾器總是生效。
run:過濾器的具體邏輯。需要注意,這裡我們通過ctx.setSendZuulResponse(false)令zuul過濾該請求,不對其進行路由,然後通過ctx.setResponseStatusCode(401)設定了其傳回的錯誤碼,當然我們也可以進一步優化我們的傳回,比如,通過ctx.setResponseBody(body)對傳回body内容進行編輯等。
*/
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
Object accessToken = request.getParameter("accessToken"); //定義規則:通路url中必須帶有accessToken參數
if(accessToken == null || !accessToken.equals(accessToken)) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
return null;
}
return null;
}
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
然後配置網關代理
#develop
# zuul配置
zuul:
host:
max-total-connections: 1000
max-per-route-connections: 100
semaphore:
max-semaphores: 500
routes:
api-a:
path: /services/**
# 提供服務的名稱,對外接口,需提供token
serviceId: arthur-manage-serviceWeb
spring:
accessToken: 1000010121385750333
最後通過網關伺服器就可以通路注冊服務提供的方法了
之前通路http://127.0.0.1:10001/getUserList?offset=1
現在通路http://127.0.0.1:9999/services/getUserList?offset=1&accessToken=1000010121385750333 同樣的效果
最後就可以同步進行開發了。