在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

SpringCloud微服务实战

2016-8-16 12:48| 发布者: zhangjf| 查看: 788| 评论: 0

摘要: 序 主要有eureka做服务发现、config做分布式配置、zuul做api-gateway、feign做客户端负载均衡、hystrix做断路器、turbine做聚合的monitor、graphite做指标监控。 eureka pom配置dependencies dependency ...

主要有eureka做服务发现、config做分布式配置、zuul做api-gateway、feign做客户端负载均衡、hystrix做断路器、turbine做聚合的monitor、graphite做指标监控。

eureka

pom配置

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-actuator</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-eureka-server</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>junit</groupId>
  16. <artifactId>junit</artifactId>
  17. <scope>test</scope>
  18. </dependency>
  19. </dependencies>
复制代码

application.yml

  1. server:
  2. port: 8761
  3. eureka:
  4. instance:
  5. hostname: discovery
  6. client:
  7. registerWithEureka: false
  8. fetchRegistry: false
  9. serviceUrl:
  10. defaultZone: http://discovery:${server.port}/eureka/
  11. spring.cloud.config.discovery.enabled: true
复制代码

bootstrap.yml

  1. spring:
  2. application:
  3. name: discovery
复制代码

application

  1. @SpringBootApplication
  2. @EnableEurekaServer
  3. public class EurekaApplication {
  4. public static void main( String[] args ) {
  5. SpringApplication.run(EurekaApplication.class, args);
  6. }
  7. }
复制代码

访问
http://192.168.99.100:8761/

config

pom配置

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-config-server</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-eureka</artifactId>
  13. </dependency>
  14. </dependencies>
复制代码

application.yml

  1. spring:
  2. cloud:
  3. config:
  4. server:
  5. native:
  6. search-locations: classpath:/config
  7. server:
  8. port: 8888
复制代码

bootstrap.yml

  1. spring:
  2. application:
  3. name: config
  4. profiles:
  5. active: native
  6. eureka:
  7. instance:
  8. preferIpAddress: true
  9. client:
  10. service-url:
  11. defaultZone: http://discovery:8761/eureka/
复制代码

application

  1. @SpringBootApplication
  2. @EnableConfigServer
  3. @EnableEurekaClient
  4. public class ConfigApplication {
  5. public static void main( String[] args ) {
  6. SpringApplication.run(ConfigApplication.class,args);
  7. }
  8. }
复制代码

访问
http://192.168.99.100:8888/review/default/master

feign实例

pom

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-web</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-actuator</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.cloud</groupId>
  16. <artifactId>spring-cloud-config-client</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.cloud</groupId>
  20. <artifactId>spring-cloud-starter-eureka</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>com.patterncat</groupId>
  24. <artifactId>common</artifactId>
  25. <version>1.0-SNAPSHOT</version>
  26. </dependency>
  27. <!--调用其他微服务-->
  28. <dependency>
  29. <groupId>org.springframework.cloud</groupId>
  30. <artifactId>spring-cloud-starter-ribbon</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.cloud</groupId>
  34. <artifactId>spring-cloud-starter-feign</artifactId>
  35. </dependency>
  36. <!--使用hystrix-->
  37. <dependency>
  38. <groupId>org.springframework.cloud</groupId>
  39. <artifactId>spring-cloud-starter-hystrix</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.cloud</groupId>
  43. <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
  44. </dependency>
  45. </dependencies>
复制代码

application.yml

  1. server:
  2. port: 9001
  3. endpoints:
  4. restart:
  5. enabled: true
  6. shutdown:
  7. enabled: true
  8. health:
  9. sensitive: false
  10. ribbon:
  11. eureka:
  12. enabled: true
复制代码

bootstrap.yml

  1. spring:
  2. application:
  3. name: product
  4. cloud:
  5. config:
  6. uri: http://config:8888
  7. encrypt:
  8. failOnError: false
  9. eureka:
  10. instance:
  11. preferIpAddress: true
  12. client:
  13. registerWithEureka: true
  14. fetchRegistry: true
  15. serviceUrl:
  16. defaultZone: http://discovery:8761/eureka/
复制代码

FeignClient

  1. @FeignClient("recommend")
  2. public interface RemoteRecommendService {
  3. @RequestMapping(method = RequestMethod.GET,value = "/recommend")
  4. public List<Recommendation> getRecommendations(
  5. @RequestParam(value = "productId", required = true) int productId);
  6. }
复制代码

feign使用

  1. @RestController
  2. public class ProductController {
  3. private static final Logger LOG = LoggerFactory.getLogger(ProductController.class);
  4. @Autowired
  5. private SetProcTimeBean setProcTimeBean;
  6. @Autowired
  7. RemoteRecommendService remoteRecommendService;
  8. @RequestMapping("/product/recommends")
  9. @HystrixCommand(fallbackMethod = "callRecommendFallback", commandProperties = {
  10. @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")
  11. })
  12. public List<Recommendation> remoteRecommends(@RequestParam(value = "productId", required = true) int productId){
  13. return remoteRecommendService.getRecommendations(productId);
  14. }
  15. public List<Recommendation> callRecommendFallback(int productId) {
  16. return Collections.emptyList();
  17. }
  18. @RequestMapping("/product/{productId}")
  19. public Product getProduct(@PathVariable int productId) {
  20. int pt = setProcTimeBean.calculateProcessingTime();
  21. LOG.info("/product called, processing time: {}", pt);
  22. sleep(pt);
  23. LOG.debug("/product return the found product");
  24. return new Product(productId, "name", 123);
  25. }
  26. }
复制代码

application

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. @EnableFeignClients
  4. @EnableCircuitBreaker
  5. @EnableHystrix
  6. @EnableHystrixDashboard
  7. public class ProductApplication {
  8. private static final Logger LOG = LoggerFactory.getLogger(ProductApplication.class);
  9. public static void main(String[] args){
  10. SpringApplication.run(ProductApplication.class,args);
  11. LOG.info("Register ShutdownHook");
  12. Runtime.getRuntime().addShutdownHook(new Thread(){
  13. @Override
  14. public void run() {
  15. LOG.info("Shutting down product service, unregister from Eureka!");
  16. DiscoveryManager.getInstance().shutdownComponent();
  17. }
  18. });
  19. }
  20. }
复制代码
api-gateway

pom

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-zuul</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-starter-eureka</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.cloud</groupId>
  16. <artifactId>spring-cloud-starter-config</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-web</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-actuator</artifactId>
  25. </dependency>
  26. </dependencies>
复制代码

application.yml

  1. server:
  2. port: 10000
  3. #sidecar:
  4. #port: 8000
  5. endpoints:
  6. restart:
  7. enabled: true
  8. shutdown:
  9. enabled: true
  10. health:
  11. sensitive: false
  12. zuul:
  13. ignored-services: "*"
  14. routes:
  15. product:
  16. path: /product/**
  17. url: http://product:9001/product
  18. recommend:
  19. path: /recommend/**
  20. url: http://recommend:9002/recommend
  21. review:
  22. path: /review/**
  23. url: http://review:9003/review
复制代码

bootstrap.yml

  1. spring:
  2. application:
  3. name: gateway
  4. cloud:
  5. config:
  6. uri: http://config:8888
  7. encrypt:
  8. failOnError: false
  9. eureka:
  10. instance:
  11. preferIpAddress: true
  12. client:
  13. registerWithEureka: true
  14. fetchRegistry: true
  15. serviceUrl:
  16. defaultZone: http://discovery:8761/eureka/
复制代码

application

  1. @SpringBootApplication
  2. @EnableCircuitBreaker
  3. @EnableDiscoveryClient
  4. @EnableZuulProxy
  5. public class ApiGatewayApplication {
  6. public static void main( String[] args ) {
  7. new SpringApplicationBuilder(ApiGatewayApplication.class).web(true).run(args);
  8. }
  9. }
复制代码

访问
http://192.168.99.100:10000/recommend?productId=1

转向
http://192.168.99.100:9002/recommend?productId=1

hystrix

http://192.168.99.100:9001/product/recommends?productId=1
http://192.168.99.100:9001/hystrix

http://192.168.99.100:9003/hystrix/monitor?stream=http%3A%2F%2F192.168.99.100%3A9001%2Fhystrix.stream

turbine

pom

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-starter</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-turbine</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-actuator</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.cloud</groupId>
  20. <artifactId>spring-cloud-config-client</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.cloud</groupId>
  24. <artifactId>spring-cloud-starter-eureka</artifactId>
  25. </dependency>
  26. <!--使用hystrix-->
  27. <dependency>
  28. <groupId>org.springframework.cloud</groupId>
  29. <artifactId>spring-cloud-starter-hystrix</artifactId>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework.cloud</groupId>
  33. <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
  34. </dependency>
  35. </dependencies>
复制代码

application.yml

  1. server:
  2. port: 8889
  3. eureka:
  4. instance:
  5. preferIpAddress: true
  6. client:
  7. registerWithEureka: true
  8. fetchRegistry: true
  9. serviceUrl:
  10. defaultZone: http://discovery:8761/eureka/
  11. turbine:
  12. appConfig: product,review
  13. clusterNameExpression: new String("default")
复制代码

bootstrap.yml

  1. spring:
  2. application:
  3. name: turbine
  4. cloud:
  5. config:
  6. uri: http://config:8888
  7. encrypt:
  8. failOnError: false
复制代码

application

  1. @SpringCloudApplication
  2. @EnableTurbine
  3. @EnableHystrixDashboard
  4. public class TurbineApplication {
  5. public static void main(String[] args){
  6. SpringApplication.run(TurbineApplication.class,args);
  7. }
  8. }
复制代码

访问

http://192.168.99.100:9001/hystrix

http://192.168.99.100:9001/product/recommends?productId=1
http://192.168.99.100:9003/review/product/100

graphite配置

pom

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-actuator</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. <scope>test</scope>
  10. </dependency>
  11. <!-- metrics -->
  12. <dependency>
  13. <groupId>io.dropwizard.metrics</groupId>
  14. <artifactId>metrics-core</artifactId>
  15. <version>${dropwizard-metrics.version}</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>io.dropwizard.metrics</groupId>
  19. <artifactId>metrics-graphite</artifactId>
  20. <version>${dropwizard-metrics.version}</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>io.dropwizard.metrics</groupId>
  24. <artifactId>metrics-annotation</artifactId>
  25. <version>${dropwizard-metrics.version}</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>io.dropwizard.metrics</groupId>
  29. <artifactId>metrics-jvm</artifactId>
  30. <version>${dropwizard-metrics.version}</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>com.ryantenney.metrics</groupId>
  34. <artifactId>metrics-spring</artifactId>
  35. <version>3.1.0</version>
  36. <exclusions>
  37. <exclusion>
  38. <artifactId>spring-beans</artifactId>
  39. <groupId>org.springframework</groupId>
  40. </exclusion>
  41. <exclusion>
  42. <artifactId>spring-aop</artifactId>
  43. <groupId>org.springframework</groupId>
  44. </exclusion>
  45. </exclusions>
  46. </dependency>
  47. </dependencies>
复制代码

configuration

  1. @Configuration
  2. @AutoConfigureAfter(MetricRepositoryAutoConfiguration.class)
  3. @ConditionalOnProperty(prefix = "graphite", name = "enabled", matchIfMissing = true)
  4. @EnableConfigurationProperties(GraphiteProperties.class)
  5. @EnableScheduling
  6. @EnableMetrics
  7. public class GraphiteAutoConfiguration {
  8. private static final Logger logger = LoggerFactory.getLogger(GraphiteAutoConfiguration.class);
  9. @Bean
  10. public MetricsConfigurerAdapter metricsConfigurerAdapter(final GraphiteProperties graphiteProperties) {
  11. return new GraphiteReportingManager(graphiteProperties);
  12. }
  13. /**
  14. * https://qbgbook.gitbooks.io/spring-boot-reference-guide-zh/content/IV.%20Spring%20Boot%20features/36.3.3.%20Property%20conditions.html
  15. * @param graphiteProperties
  16. * @param metricRegistry
  17. * @return
  18. */
  19. @Bean
  20. @ConditionalOnProperty(value = "graphite.host",matchIfMissing = true)
  21. public ConsoleReporter consoleReporter(GraphiteProperties graphiteProperties,MetricRegistry metricRegistry) {
  22. ConsoleReporter.Builder builder = ConsoleReporter.forRegistry(metricRegistry);
  23. ConsoleReporter reporter = builder.build();
  24. reporter.start(graphiteProperties.getReportInterval(), TimeUnit.MILLISECONDS);
  25. return reporter;
  26. }
  27. }
复制代码

report

  1. public class GraphiteReportingManager extends MetricsConfigurerAdapter implements DisposableBean {
  2. private final Logger logger = LoggerFactory.getLogger(getClass());
  3. private GraphiteProperties props;
  4. public GraphiteReportingManager(GraphiteProperties props) {
  5. this.props = props;
  6. }
  7. @Override
  8. public void configureReporters(MetricRegistry metricRegistry) {
  9. //gc的metrics,目前看来每秒发送一次貌似太频繁,可以另起一个reporter进行
  10. metricRegistry.register("jvm.gc", new GarbageCollectorMetricSet());
  11. metricRegistry.register("jvm.mem", new MemoryUsageGaugeSet());
  12. metricRegistry.register("jvm.thread-states", new ThreadStatesGaugeSet());
  13. logger.info("graphite host:{},port:{}", props.getHost(), props.getPort());
  14. GraphiteReporter reporter = GraphiteReporter.forRegistry(metricRegistry)
  15. .prefixedWith(props.getPrefix())
  16. // .convertRatesTo(TimeUnit.SECONDS)
  17. .convertDurationsTo(TimeUnit.MILLISECONDS)
  18. .filter(MetricFilter.ALL)
  19. .build(createSender(props));
  20. registerReporter(reporter);
  21. reporter.start(1L, TimeUnit.SECONDS);
  22. }
  23. @Override
  24. public void destroy() throws Exception {
  25. super.destroy();
  26. }
  27. private GraphiteSender createSender(GraphiteProperties props) {
  28. switch (props.getSenderType()) {
  29. case udp:
  30. return new GraphiteUDP(props.getHost(), props.getPort());
  31. case tcp:
  32. return new Graphite(props.getHost(), props.getPort());
  33. case pickled:
  34. return new PickledGraphite(props.getHost(), props.getPort());
  35. default:
  36. return new GraphiteUDP(props.getHost(), props.getPort());
  37. }
  38. }
  39. }
复制代码

访问

http://192.168.99.100:8070/

参考

Blog Series - Building Microservices

git.blog-microservices

exposing-jvm-metrics-in-spring-boot

git.spring-boot-jvm-monitoring-demo

exporting-to-graphite-with-the-prometheus-java-client

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 15:32

Copyright 2015-2025 djqfx

返回顶部