zoukankan      html  css  js  c++  java
  • spring cloud Provider:9003-Ek:9001-Zuul:9002-Consumer hystrix :9004-ZipKinServer:9006-Gateway:9007-EK9008:9008 Consul:8500-CS:9009-CC:9010 SG:9011 InStream:9012-OutStream:9013

      

      

      

      

      

    1、EK
    ###9001##################
    ###http://localhost:9001/

    ###9008##################
    ###http://localhost:9008/
    #########################

      1-1、pom.xml
        <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
          <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
          </dependency>
          <dependencyManagement>
            <dependencies>
              <dependency>
               <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
              </dependency>
            </dependencies>
          </dependencyManagement>
      1-2、application.properties

         

        server.port=9001
        spring.application.name=eureka
        eureka.instance.hostname=localhost
        eureka.client.register-with-eureka=false
        eureka.client.fetch-registry=false
        eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

      1-3、EkApplication.java

        @EnableEurekaServer
        @SpringBootApplication


    2、ZL

    ###9002########################################
    ###http://localhost:9002/provider/hello########
    ###http://localhost:9002/consumer/get-greeting
    ###############################################

      2-1、pom.xml
      <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependencyManagement>
          <dependencies>
            <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
            </dependency>
          </dependencies>
        </dependencyManagement>

      2-2、application.properties

        server.port=9002
        server.address=localhost
        spring.application.name=apiGeteway

        #服务注册地址
        eureka.instance.ip-address=localhost
        eureka.instance.prefer-ip-address=true
        eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

        #路由配置
        #url形式
        zuul.routes.baidu.path=/baidu/**
        zuul.routes.baidu.url==http://www.baidu.com

       

      #注册服务provider####
      zuul.routes.provider.path=/provider/**
      zuul.routes.provider.service-id=provider

      #consumer####
      zuul.routes.api-feign.service-id=consumer
      zuul.routes.api-feign.path=/consumer/*

      2-3、EkApplication.java

        @EnableZuulProxy
        @SpringBootApplication

        

        @Bean
        public zlFilter myFilter(){
          return new zlFilter();
        }

      2-4、zlFilter
      public class zlFilter extends ZuulFilter {


        @Override
        public String filterType() {
          return "pre";
        }


        @Override
        public int filterOrder() {
          return 0;
        }


        @Override
        public boolean shouldFilter() {
          return true;
        }


        @Override
        public Object run() throws ZuulException {
          RequestContext ctx = RequestContext.getCurrentContext();
          HttpServletRequest request = ctx.getRequest();
          String token = request.getParameter("token");
          if (token == null || token.isEmpty()) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("token is empty");
          }
          return null;
        }
      }

    3、provider 9003

    ###9003################################################
    ###http://localhost:9003/hello################################
    ###http://localhost:9002/provider/hello#########################
    ###zlFilter                   ##############
    ###http://localhost:9002/provider/hello?token=12################
    #######################################################

      3-1、pom.xml
        <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
          <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
          </dependency>

                          <!--与eureka-client 二选一 -->

          <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
          </dependency>


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

           <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-zipkin</artifactId>
          </dependency>


          <dependencyManagement>
            <dependencies>
            <dependency>
              <groupId>org.springframework.cloud</groupId>
              <artifactId>spring-cloud-dependencies</artifactId>
              <version>${spring-cloud.version}</version>
              <type>pom</type>
              <scope>import</scope>
            </dependency>
          </dependencies>
        </dependencyManagement>

      3-2、application.properties

        server.port=9003
        server.address=localhost
        spring.application.name=provider

        #服务注册地址
        eureka.instance.ip-address=localhost
        eureka.instance.prefer-ip-address=true
        eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/,http://localhost:9008/eureka/

        #zipkin服务地址
        spring.zipkin.base-url=http://localhost:9006
        #全部集采
        spring.sleuth.sampler.probability=1.0

        

        #consul服务注册地址

        spring.cloud.consul.host=localhost
        spring.cloud.consul.port=8500
        spring.cloud.consul.discovery.register=true
        spring.cloud.consul.discovery.service-name=provider
        #注册实例ID(必须唯一)
        spring.cloud.consul.discovery.instance-id=provider-01
        #spring.cloud.consul.discovery.health-check-path=${management.contextPath}/health
        #spring.cloud.consul.discovery.health-check-interval=10s
        spring.cloud.consul.discovery.prefer-ip-address=true
        spring.cloud.consul.discovery.ip-address=localhost
        #<artifactId>spring-boot-starter-actuator</artifactId>
        #spring.cloud.consul.discovery.health-check-path=/actuator/health
        #spring.cloud.consul.discovery.hostname=localhost
        #spring.cloud.consul.discovery.healthCheckUrl=http://192.168.0.240:9113/actuator/health

      3-3、ProviderApplication.java

        

        @EnableEurekaClient
        @SpringBootApplication
        @EnableDiscoveryClient
        //@Configuration

      3-4、Controller
        package com.sc.provider.controller;
        @RestController
        public class HelloController {
          @GetMapping("/hello")
        public String hello(){
          

        "Hello World from Provider:9003;to Ek:9001;to Zuul:9002;to Consumer:9004;" +
        ZipKinServer:9006";


        }
      }


    4、consumer  9004

    ###9004#########################################
    ###http://localhost:9004/get-greeting###################
    ###http://localhost:9004/get-greetin2###################

    ###http://localhost:9004/get-greetin3###################
    ###http://localhost:9004/services######################
    ###http://localhost:9004/discover######################
    ###http://localhost:9002/consumer/get-greeting###########

    ###zlFilter             ####################
    ###http://localhost:9002/consumer/get-greeting?token=12####

    #########手写@LoadBalanced#########################

    ###http://localhost:9004/discover2#######################

    ##################################################

      4-1、pom.xml
      <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
      <dependency>
      <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      </dependency>

            <!--与eureka-client 二选一 -->

      <dependency>
      <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-discovery</artifactId>
      </dependency>


      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
      </dependency>

      <--!断路器Hystrix--无效服务中断-->
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zipkin</artifactId>
      </dependency>
      <!--提示 unable to connect to Command Metric Stream-->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>


      <dependencyManagement>
        <dependencies>
          <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
            </dependency>
        </dependencies>
      </dependencyManagement>

      4-2、application.properties

        server.port=9004
        server.address=localhost
        spring.application.name=consumer

        #服务注册地址
        eureka.instance.ip-address=localhost
        eureka.instance.prefer-ip-address=true
        eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

                 

        #断路器#########无效服务中断####
        feign.hystrix.enabled=true

        #zipkin服务地址
        spring.zipkin.base-url=http://localhost:9006
        #全部集采
        spring.sleuth.sampler.probability=1.0

        

        #consul服务注册地址
        spring.cloud.consul.host=localhost
        spring.cloud.consul.port=8500
        #设置不需要注册到consul
        spring.cloud.consul.discovery.register=false
        spring.cloud.consul.discovery.service-name=consumer-01
        spring.cloud.consul.discovery.instance-id=consumer
        #spring.cloud.consul.discovery.health-check-path=${management.contextPath}/health
        #spring.cloud.consul.discovery.health-check-interval=10s
        spring.cloud.consul.discovery.prefer-ip-address=true
        spring.cloud.consul.discovery.ip-address=localhost
        #<artifactId>spring-boot-starter-actuator</artifactId>
        #spring.cloud.consul.discovery.health-check-path=/actuator/health

      

      4-3、ConsumerApplication.java

                  @EnableDiscoveryClient

        @EnableFeignClients
        @EnableEurekaClient
        @SpringBootApplication

        @EnableCircuitBreaker //启动断路器,监控hystrix流
      4-4、HelloClient

      package com.sc.consumer.client;

      /**
      * Feign远程端口
      */
       @FeignClient(value = "provider",fallback =HelloClientImpl.class)
      public interface HelloClient {
        @LoadBalanced
        @GetMapping("/hello")
      public String hello();
      }

            #####1@FeiC   fallback############
      package com.sc.consumer.client.impl;
      @Component
      public class HelloClientImpl implements HelloClient {
        @Override
        public String hello() {
          return "Provider:9003 Error,请核对!     1@FeiC";
        }
      }

      package com.sc.consumer.service;
      import com.sc.consumer.client.HelloClient;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;

      @Service
      public class HelloService {
      @Autowired
      private HelloClient helloClient;

        public String hello() {
          return helloClient.hello();
        }
      }

      4-5、GreetingController

       

        @Autowired
        private HelloClient helloClient;

        @Autowired
        private HelloService helloService;

        @Autowired
        private DiscoveryClient discoveryClient;

        @Autowired
        private LoadBalancerClient loadBalancerClient;

        @GetMapping("/get-greeting")
        public String greeting() {
          return helloClient.hello() + " to consumer";
        }

        @GetMapping("/get-greeting2")
        public String greeting2() {
          return helloService.hello();
        }

        #####2HyCom fallback############
        @HystrixCommand(fallbackMethod = "greeting3Error")
        @GetMapping("/get-greeting3")
        public String greeting3() {
          return helloClient.hello() + " to consumer 3";
        }

        public String greeting3Error(){
          return "greeting3Error srroy.error!    2HyCom";
        }

        @GetMapping("/services")
        public Object services() {
          return discoveryClient.getInstances("provider");
        }

        @GetMapping("/discover")
        public Object discover() {
          return loadBalancerClient.choose("provider").getUri().toString();
        }

      4-6、手写@LoadBalanced
        @RestController
        public class LoadBalancedController {
                    @Autowired
          private DiscoveryClient discoveryClient;
          @Autowired
          private RestTemplate restTemplate;
          private int reqNum=1;

          @GetMapping("/discover2")
          public Object discover() {
            String uri=serviceUri()+"/hello";
            System.out.println(......"uri:"+uri);
            return restTemplate.getForObject(uri,String.class);
          }


          private String serviceUri(){
            List<ServiceInstance> serviceInstanceList=discoveryClient.getInstances("provider");
            if(serviceInstanceList==null||serviceInstanceList.size()==0){
              return null;
            }

            int num=serviceInstanceList.size();
            int serviceIndex=reqNum%num;
            reqNum++;
            return serviceInstanceList.get(serviceIndex).getUri().toString();
          }

         }

      4-7、config
      @Configuration
      public class RestTemplateConfig {
        @Bean
        public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
          return new RestTemplate(factory);
        }

        @Bean
        public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
          SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
          factory.setReadTimeout(5000);//ms
          factory.setConnectTimeout(15000);//ms
          return factory;
        }
      }

        ############################
        ############################
        ############HystrixCommand##
        ####@EnableCircuitBreaker //启动断路器,监控hystrix流
        ############################
        ############################
        4-8、HelloCommand

        package com.sc.consumer.hystrix;
        import com.netflix.hystrix.HystrixCommand;
        import com.netflix.hystrix.HystrixCommandGroupKey;
        import com.netflix.hystrix.HystrixCommandProperties;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.cloud.client.ServiceInstance;
        import org.springframework.cloud.client.discovery.DiscoveryClient;
        import org.springframework.web.client.RestTemplate;
        import java.util.List;
        import java.util.concurrent.ExecutionException;
        import java.util.concurrent.Future;


        public class HelloCommand extends HystrixCommand<String> {
          private RestTemplate restTemplate;
          private DiscoveryClient discoveryClient;
          private Long id;
          private int reqNum=1;

          public HelloCommand(HystrixCommand.Setter setter, RestTemplate restTemplate, Long id){
            super(setter);
            this.restTemplate = restTemplate;
            this.id = id;
          }

          /**
          * 注意本地main方法启动,url请用http://localhost:8080/user
          * 通过controller请求启动需要改为服务调用地址:http://eureka-service/user
          */
          @Override
          protected String run() {
          //本地请求
          //return restTemplate.getForObject("http://localhost:8080/user", User.class);
          //连注册中心请求
          //String uri=serviceUri()+"/hello";
          //return restTemplate.getForObject(uri, String.class);
          return restTemplate.getForObject("http://localhost:9003//hello", String.class);
               /**      * 此方法为《spirngcloud微服务实战》中的学习部分,仅用于在此项目启动的之后调用本地服务,但是不能没有走注册中心。

          * 书中为我们留下了这个坑,详情请直接翻阅151页。
          * 问题解决请参考:https://blog.csdn.net/lvyuan1234/article/details/76550706
          * 本人在书中基础上已经完成调用注册中心服务的功能,见RibbonService类中具体实现
          */
          public static void main(String[] args) {
            //同步请求
            String stringSync=new HelloCommand(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(
            HystrixCommandGroupKey.Factory.asKey("")).andCommandPropertiesDefaults(
            HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(5000)),new RestTemplate(),0L).execute();
            System.out.println("------------------This is sync request's response:"+stringSync);
            //异步请求
            Future<String> stringFuture = new HelloCommand(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(
            HystrixCommandGroupKey.Factory.asKey("")).andCommandPropertiesDefaults(
            HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(5000)),new RestTemplate(),0L).queue();

            String stringAsync = null;

            try {
            stringAsync = stringFuture.get();
            } catch (InterruptedException e) {
              e.printStackTrace();
            } catch (ExecutionException e) {
              e.printStackTrace();
            }
            System.out.println("------------------This is async request's response:"+stringAsync);
          }
        }


    4-9、RibbonService
        package com.sc.consumer.service;
        import com.netflix.hystrix.HystrixCommandGroupKey;
        import com.netflix.hystrix.HystrixCommandProperties;
        import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
        import com.sc.consumer.hystrix.HelloCommand;
        import org.apache.logging.log4j.Logger;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.cloud.client.ServiceInstance;
        import org.springframework.cloud.client.discovery.DiscoveryClient;
        import org.springframework.stereotype.Service;
        import org.springframework.web.client.RestTemplate;
        import javax.swing.plaf.synth.SynthTextAreaUI;
        import java.util.List;
        import java.util.Random;
        import java.util.concurrent.ExecutionException;
        import java.util.concurrent.Future;

        @Service
        public class RibbonService {
          //private static final Logger logger=
          @Autowired
          RestTemplate restTemplate;
          @Autowired
          private DiscoveryClient discoveryClient;
          private int reqNum=1;

        /**
          * 使用Hystrix注解,声明回调类,此方法为同步请求,如果不指定回调方法会使用默认
          */
        @HystrixCommand(fallbackMethod = "hystrixFallback")
        public String helloService(){
          long start = System.currentTimeMillis();
          //设置随机3秒内延迟,hystrix默认延迟2秒未返回则熔断,调用回调方法
          int sleepMillis = new Random().nextInt(3000);
          System.out.println("----sleep-time:"+sleepMillis);

          try {
            Thread.sleep(sleepMillis);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

          //调用服务提供者接口,正常则返回hello字符串
          String uri=serviceUri()+"/hello";
          uri="http://localhost:9003//hello";
          String body = restTemplate.getForEntity(uri, String.class).getBody();
          long end = System.currentTimeMillis();
          System.out.println("----spend-time:"+(end-start));
          return body;
        }

        /**
        * 调用服务失败处理方法:返回类型为字符串
        * @return “error"
        */
        public String hystrixFallback(){
          return "error";
        }

        private String serviceUri(){
          List<ServiceInstance> serviceInstanceList=discoveryClient.getInstances("provider");
          if(serviceInstanceList==null||serviceInstanceList.size()==0){
            return null;
          }
          int num=serviceInstanceList.size();
          int serviceIndex=reqNum%num;
          reqNum++;
          return serviceInstanceList.get(serviceIndex).getUri().toString();
        }

        /**
          * 使用自定义HystrixCommand同步方法调用接口
        */
        public String useSyncRequestGetUser(){
          //这里使用Spring注入的RestTemplate, Spring注入的对象都是静态的
          String stringSync = new HelloCommand(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(
          HystrixCommandGroupKey.Factory.asKey("")).andCommandPropertiesDefaults(
          HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(15000)),
          restTemplate ,0L).execute();

          return stringSync;
        }

        /**
        * 使用自定义HystrixCommand异步方法调用接口 string
        */
        public String useAsyncRequestGetUser(){

          Future<String> stringFuture = new HelloCommand(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(
          HystrixCommandGroupKey.Factory.asKey("")).andCommandPropertiesDefaults(
          HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(15000)),
          restTemplate,0L).queue();

          String stringAsync = null;

          try {
            //获取Future内部包含的对象
            stringAsync = stringFuture.get();
          } catch (InterruptedException e) {
            e.printStackTrace();
          } catch (ExecutionException e) {
           e.printStackTrace();
          }

          return stringAsync;
        }


       }

    4-10、RibbonController

        package com.sc.consumer.controller;
        import com.sc.consumer.service.RibbonService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.GetMapping;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;
        import java.util.concurrent.ExecutionException;
        import java.util.concurrent.Future;

        @RestController
        @RequestMapping("hystrix")
        public class RibbonController {
          @Autowired
          RibbonService service;

          @GetMapping("/invoke")
          public String helloHystrix(){
            //调用服务层方法
            return service.helloService();
          }

          /**
          * 发送同步请求,使用继承方式实现自定义Hystrix
          */
        @GetMapping("/sync")
        public String sendSyncRequestGetUser(){
          return service.useSyncRequestGetUser();
        }

        /**
        *发送异步请求,使用继承方式实现自定义Hystrix
        */
        @GetMapping("/async")
        public String sendAsyncRequestGetUser(){
          return service.useAsyncRequestGetUser();
          }
      }

    6、zipkinserver 9006
    ###9411################################
    ###http://localhost:9006/
      spring Cloud为F版本的时候,已经不需要自构Zipkin Server了,
      只需下载jar即可,下载地址:
      https://dl.bintray.com/openzipkin/maven/io/zipkin/java/zipkin-server/
      也可下载:
      链接: https://pan.baidu.com/s/1w614Z8gJXHtqLUB6dKWOpQ 密码: 26pf
      运行jar,如下:
      java -jar D:softzipkin-server-2.12.9-exec.jar --server.port=9006
      浏览器http://localhost:9006/zipkin/

    7、gateway 9007

    ###9007################################
    ###http://localhost:9007/provider/hello
    ###http://localhost:9007/consumer/get-greeting
    #######################################
      7-1、pom.xml
      <dependencies>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        
      </dependencies>
      7-2、application.properties
        server.port=9007
        spring.application.name=gateway

        #服务注册地址
        eureka.instance.ip-address=localhost
        eureka.instance.prefer-ip-address=true
        eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

        #使用服务发现路由
        spring.cloud.gateway.discovery.locator.enabled=true
        #服务路由名小写
        spring.cloud.gateway.discovery.locator.lower-case-service-id=true

        #设置路由ID
        spring.cloud.gateway.routes[0].id=provider
        #设置路由URI
        spring.cloud.gateway.routes[0].uri=lb://provider
        #设置路由断言,代理servicerId为auth-service的/auth/路径
        spring.cloud.gateway.routes[0].predicates[0]= Path=/provider/**
        spring.cloud.gateway.routes[0].filters[0]= StripPrefix=1

        #设置路由ID
        spring.cloud.gateway.routes[1].id=consumer
        #设置路由URI
        spring.cloud.gateway.routes[1].uri=lb://consumer
        #设置路由断言,代理servicerId为auth-service的/auth/路径
        spring.cloud.gateway.routes[1].predicates[0]=Path=/consumer/**
        spring.cloud.gateway.routes[1].filters[0]=StripPrefix=1


      7-3、
      @EnableEurekaClient
      @SpringBootApplication
      public class GetewayApplication {

      public static void main(String[] args) {
        SpringApplication.run(GetewayApplication.class, args);
      }

      }

      7-4、
      public class RoutesConfiguration {
      @Bean
      public RouteLocator routeLocator(RouteLocatorBuilder builder){
        return builder.routes().route(predicateSpec -> predicateSpec.path("/provider/**")
    .      uri("lb://provider").id("provider")).build();
        }
      }

    8、EK eureka

    ###9008##################

    ###http://localhost:9008/

    ###9001##################

    ###http://localhost:9001/

    #########################

    8-1、pom.xml

            <spring-cloud.version>Hoxton.SR3</spring-cloud.version>

            <dependency>

                <groupId>org.springframework.cloud</groupId>

                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>

            </dependency>

             <dependencyManagement>

                    <dependencies>

                        <dependency>

                            <groupId>org.springframework.cloud</groupId>

                            <artifactId>spring-cloud-dependencies</artifactId>

                            <version>${spring-cloud.version}</version>

                            <type>pom</type>

                            <scope>import</scope>

                        </dependency>

                    </dependencies>

             </dependencyManagement>

    8-2、application.properties

        server.port=9008

        #服务注册地址

        eureka.instance.ip-address=localhost

        eureka.instance.prefer-ip-address=true

        #eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/

        eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

        #在默认设置下、该服务注册中心也会将自己作为客户端来尝试注册它自己,所有我们需要禁用它的客户端行为

        eureka.client.register-with-eureka=true

        eureka.client.fetch-registry=true

    8-3、EkApplication.java

        @EnableEurekaServer

        @SpringBootApplication

    ###9001##################
    ###http://localhost:9001/

    9、Consul
    ##################8500#####################################
      9-1、启动
      E:EEconsul_1.7.3_windows_amd64consul.exe agent -dev
        ####http://localhost:8500

    10、CS
      #############9009################################
      #############config server#######################
      http://localhost:9009/config-client-dev.properties
      http://localhost:9009/config-client/dev

      #########################################################
        git:https://github.com/sf2014/sc-config.git#######################
      ###############config-client-dev.properties#####################
          https://github.com/sf2014/sc-config/client1/config-client-dev.properties
      #########################################################
      #########################################################

      10-1、pom.xml

       <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
       </dependency>
      <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-config-server</artifactId>
      </dependency>

      

      <!--临控-->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--bus-amqp-->
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-bus-amqp</artifactId>
          <version>2.2.0.RELEASE</version>
        </dependency>


      10-2、application.properties

        server.port=9009
        spring.application.name=config-server

        #eureka服务注册地址
        eureka.instance.ip-address=localhost
        eureka.instance.prefer-ip-address=true
        #eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/,http://localhost:9008/eureka/
        eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

        #连接GitHub
        #https://github.com/sf2014/sc-config.git
        spring.cloud.config.server.git.uri=https://github.com/sf2014/sc-config.git
        spring.cloud.config.server.git.search-paths=client1 #git 新建目录client         config-client-dev.properties
        spring.cloud.config.label=master
        spring.cloud.config.server.git.username=sf2014@qq.com
        spring.cloud.config.server.git.password=sf2014git

        ##开启消息跟踪bus-amqp
        spring.cloud.bus.trace.enabled=true
        spring.rabbitmq.host=localhost
        spring.rabbitmq.port=5672
        spring.rabbitmq.username=guest
        spring.rabbitmq.password=guest

      10-3、CsApplication.java

        @EnableConfigServer
        @EnableEurekaClient
        @SpringBootApplication


    11、CC
        #############9010################################
        #############config client#######################
          http://localhost:9010/foo

        #################################################
        #################################################

          ConfigServer:http://localhost:9009配置变化,需要
          actuator/refresh手动刷新同步
          actuator/bus-refresh手动刷新同步( bus-amqp)


          i)、 Controller=>@RefreshScope //actuator
          ii)、 Post=>http://localhost:9010/actuator/refresh
            postman
          iii)、 curl -X POST http://localhost:9010/actuator/refresh
            actuator
          iiii)、curl -X POST http://localhost:9010/actuator/bus-refresh
          bus-refresh iii) actuator 可能不能用了

        ###################################################
        ###################################################

      11-1、pom.xml
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-config</artifactId>
          <version>2.2.2.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--临控-->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--bus-amqp-->
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-bus-amqp</artifactId>
          <version>2.2.0.RELEASE</version>
        </dependency>

      11-2、bootstrap.properties
      server.port=9010
      spring.application.name=config-client

      ####config###########################
      spring.cloud.config.profile=dev
      spring.cloud.config.label=master
      spring.cloud.config.uri=http://localhost:9009

      #eureka服务注册地址
      eureka.instance.ip-address=localhost
      eureka.instance.prefer-ip-address=true
      #eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/,http://localhost:9008/eureka/
      eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

      #访问端点根路径,默认为/actuator
      management.endpoints.web.base-path=/actuator
      #需要开启的端点,这里主要用到是refresh这个端点
      management.endpoints.web.exposure.include=bus-refresh
      #不需要开启的端点
      #management.endpoints.web.exposure.exclude=

      ##开启消息跟踪bus-amqp
      spring.cloud.bus.trace.enabled=true
      spring.rabbitmq.host=localhost
      spring.rabbitmq.port=5672
      spring.rabbitmq.username=guest
      spring.rabbitmq.password=guest

      11-3、ConfigconsumerApplication

        @SpringBootApplication

        @RefreshScope //actuator
        @RestController
        @EnableEurekaClient
        public class ConfigconsumerApplication {

          public static void main(String[] args) {
          SpringApplication.run(ConfigconsumerApplication.class, args);
         }

        @Value("${foo}")
        String foo;

        @RequestMapping(value = "/foo")
          public String hi(){
          return foo;
        }
      }

    12、SG
      #############9011##################################
      ###################################################
        http://localhost:9011/swagger-ui.html


      12-1、pom.xml
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency> <!-- API -->
        <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>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.2.2.RELEASE</version>
      </dependency>


      12-2、SwaggerConfig


      package com.sc.sg;
      @Configuration
      @EnableSwagger2
      public class SwaggerConfig {
        @Bean
        public Docket createRestApi() {


          System.out.println("====== SWAGGER CONFIG ======");
          return new Docket(DocumentationType.SWAGGER_2)
          .apiInfo(apiInfo()).select()
    .      apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
          .paths(PathSelectors.any())
          .build();
        }

        private ApiInfo apiInfo() {
          return new ApiInfoBuilder().title("Fast 疾速开发 RESTful APIs")
              .description("快速上手,快速开发,快速交接").contact(new Contact("geYang", "https://my.oschina.net/u/3681868/home", "572119197@qq.com"))
          .version("1.0.0").build();
        }
      }

      12-3、WebApiConfig
      package com.sc.sg;


      @Configuration
      public class WebApiConfig extends WebMvcConfigurationSupport {


        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        // 解决 SWAGGER 404报错
          registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
          registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }

        @Override
        public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

        }
      }

      12-4、TestController
      package com.sc.sg;
      @RestController
      @Api(tags = "test相关接口", description = "提供test相关的 Rest API")
      public class TestController {
        @ApiOperation("find test接口")
        @GetMapping("/find/{id}")
        public String findById(@PathVariable("id") int id) {
          return "findById";
        }
      }

      12-5、application.properties
      server.port=9011
      server.address=localhost
      spring.application.name=sg


      #eureka服务注册地址
      eureka.instance.ip-address=localhost
      eureka.instance.prefer-ip-address=true
      eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/

      12-6、SgApplication
      package com.sc.sg;


      @EnableEurekaClient
      @SpringBootApplication
      @EnableSwagger2
      public class SgApplication {
        public static void main(String[] args) {
        SpringApplication.run(SgApplication.class, args);
        }
      }

      13、其他
      13-1、安装curl
        https://winampplugins.co.uk/curl/
      13-2、rabbitmq
      http://localhost:15672/#/
      guest/guest

    ###

        14、instream
        #############9012##################################
        ###################################################

        14-1、pom.xml
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
          <version>3.0.7.RELEASE</version>
        </dependency>

       14-2、application.properties
        server.port=9012
        spring.application.name=instream

        ##开启消息amqp
        spring.rabbitmq.host=localhost
        spring.rabbitmq.port=5672
        spring.rabbitmq.username=guest
        spring.rabbitmq.password=guest

        ###分组######################
        # http://localhost:15672
        # Queues   saveOrder.groupA
        #      saveOrder.groupB
        spring.cloud.stream.bindings.saveOrder.group=groupB
        spring.cloud.stream.bindings.saveOrder.content-type=application/json

       14-3、SkinReceiverService
        /*
        消息监听类
        */
        //实现对定义了多个@Input和@Output的接口实现对通道的绑定
        // Sink定义了@Input 我们自己处理时是自己定义接口
        @EnableBinding(Sink.class)
        public class SkinReceiverService {
          private static Logger logger=LoggerFactory.getLogger(SkinReceiverService.class);
          //对input信息监听处理
          @StreamListener(Sink.INPUT)
          public void receiver(Object message){
            logger.info(message.toString());
          }
        }

        14-4、OrderMQInputChannel //定义通道
        public interface OrderMQInputChannel {
          String saveOrderChannelName="saveOrder";//通道名称
          @Input(saveOrderChannelName)//定义输入通道
          public SubscribableChannel saveOrder();
        }

        14-5、OrderMQReceiverService
        //通过绑定器 对OrderMQInputChannel通道进行绑定
        @EnableBinding(OrderMQInputChannel.class)
        public class OrderMQReceiverService {
          private static Logger logger=LoggerFactory.getLogger(OrderMQReceiverService.class);
          //对OrderMQInputChannel.saveOrderChannelName信息监听处理
          @StreamListener(OrderMQInputChannel.saveOrderChannelName)
          public void receiver(Object message){
            logger.info(message.toString());
          }
        }


        14-6、InstreamApplication
        注: RabbitMQ发信息
        http://localhost:15672
        

        Queues:Publist Message=>Console 显示对应Message信息


        15、outstream
        #############9013##################################
        ###################################################
        15-1、pom.xml
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
          <version>3.0.7.RELEASE</version>
        </dependency>
        <dependency>
        <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        15-2、application.properties
        server.port=9013
        spring.application.name=outstream

        ##开启消息amqp
        spring.rabbitmq.host=localhost
        spring.rabbitmq.port=5672
        spring.rabbitmq.username=guest
        spring.rabbitmq.password=guest

        15-3、OrderMQOutputChannel
        //定义通道
        public interface OrderMQOutputChannel {
          String saveOrderChannelName="saveOrder";//通道名称
          @Output(saveOrderChannelName)//定义输入通道
          MessageChannel saveOrder();
        }

        15-3、OrderMQOutputChannel
        //定义通道
        public interface OrderMQOutputChannel {

        }


        15-4、OrderChannelBindConfig
        //绑定通道OrderMQOutputChannel
        @EnableBinding(OrderMQOutputChannel.class)
          public class OrderChannelBindConfig {

        }

        15-5、TestController.java
        ###http://localhost:9013/saveOrder
        ###14-6、 #######
        ##Console 显示对应Message信息#######
        ## order msg order msg #######
        ####################################


        //发送信息
        @Controller
        public class TestController {
          @Autowired
          OrderMQOutputChannel orderMQOutputChannel;
          @Autowired@Qualifier(OrderMQOutputChannel.saveOrderChannelName)
          MessageChannel messageChannel;


          @RequestMapping("/saveOrder")
          @ResponseBody
          public boolean saveOrder(){
            //发送一条保存订单的命令
            //return orderMQOutputChannel.saveOrder().send(MessageBuilder.withPayload("order msg").build());
            return messageChannel.send(MessageBuilder.withPayload("order msg").build());
          }
        }

  • 相关阅读:
    关于切图的一道题目
    spm3 基本
    简易路由操作
    IOS 技术层概览
    IOS -C基础
    prototype演变
    css3选择器总结
    Python核心编程(第二版) 第五章习题答案
    Python核心编程(第二版) 第四章习题答案
    Python核心编程(第二版) 第三章习题答案
  • 原文地址:https://www.cnblogs.com/smallfa/p/12782061.html
Copyright © 2011-2022 走看看