Consul、Eureka、Spring Cloud Zookeeper

      • Consul

      安装

      ./consul agent -dev -client=0.0.0.0 dev模式启动。会控制台输出各种debug信息

      ./consul members 查看集群成员

      ./consul join 192.168.3.50  加入集群

      ./consul leave  退出集群

      1. Order服务

      application.yml

      server:
        port: 8082
      
      spring:
        application:
          name: order   //定义注册到consul上的名字
        cloud:
          consul:
            host: 192.168.3.223  //consul的ip
            port: 8500           //consul端口号
            discovery:
              instance-id: ${spring.application.name}:${server.port}   //实例的id,不要重复就行,甚至可以使用random 
              health-check-interval: 10s   //监控检查的时间
              health-check-headers:
                X-Config-Token: 6442e58b-d1ea-182e-cfa5-cf9cddef0722    //这个是健康检查的时候自定义的数据,可以用于权限验证
              health-check-url: http://192.168.3.214:8082/              //验证健康的路径
              tags: foo=bar, baz=1                                      //自定义的tags

      ConsulOrderApplication.java

      @SpringBootApplication
      @RestController                  //启用rest接口
      @EnableDiscoveryClient           //启用consul
      public class ConsulOrderApplication {
      
          @RequestMapping("/")
          public String home() {
              return "Hello world";
          }
      
          @RequestMapping("/getDate")
          public long getDate() {
              return System.currentTimeMillis();
          }
      
          public static void main(String[] args) {
              SpringApplication.run(ConsulOrderApplication.class, args);
          }
      }

      1. User服务

      bootstrap.yml

      spring:
        cloud:
          consul:
            host: 192.168.3.223
            #host: 00.0.100.200
            port: 8500
            #enabled将此值设置为“false”禁用Consul配置
            config:
              enabled: true   #默认是true --
              format: YAML    # 表示consul上面文件的格式 有四种 YAML PROPERTIES KEY-VALUE FILES
              #data-key: configuration    #表示consul上面的KEY值(或者说文件的名字) 默认是data
              data-key: data    #表示consul上面的KEY值(或者说文件的名字) 默认是data
              #prefix设置配置值的基本文件夹
              #defaultContext设置所有应用程序使用的文件夹名称
              #profileSeparator设置用于使用配置文件在属性源中分隔配置文件名称的分隔符的值
              watch:
                enabled: true
                delay: 1000

      application-dev.yml文件加载的优先级很低,consul的配置信息必须要写在bootstrap.yml中

      application.yml

      spring:
        profiles:
          active: dev

      application-dev.yml

      server:
        port: 8081
      
      spring:
        application:
          name: user
        cloud:
          consul:
            discovery:
              instance-id: ${spring.application.name}:${server.port}
              health-check-interval: 10s
              health-check-headers:
                X-Config-Token: 6442e58b-d1ea-182e-cfa5-cf9cddef0722
              health-check-url: http://192.168.3.214:8081/
              tags: foo=bar, baz=1
              prefer-ip-address: true
              prefer-agent-address: true
      
          loadbalancer:
            ribbon:
              enabled: true
      
      feign:
        hystrix:
          enabled: true   #feign启动hystrix
      
      management:
        endpoints:
          web:
            exposure:
              include: '*'
      turbine:
        aggregator:
          clusterConfig: ${spring.application.name}
        appConfig: ${spring.application.name}       #clusterConfig和appConfig部分必须匹配,因此将逗号分隔的服务标识列表放在单独的配置属性中是有用的。
        cluster-name-expression: new String("default")

      UserConfig.java

      @ConfigurationProperties(prefix = "student")
      public class UserConfig {
          private String name;
          private  int age;
          private String sex;
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          public String getSex() {
              return sex;
          }
      
          public void setSex(String sex) {
              this.sex = sex;
          }
      
          @Override
          public String toString() {
              return "StudentConfig{" +
                      "name='" + name + '\'' +
                      ", age=" + age +
                      ", sex='" + sex + '\'' +
                      '}';
          }
      }

      ConsulUserApplication.java

      @SpringBootApplication
      @RestController
      @RequestMapping("/test")
      @EnableDiscoveryClient
      @EnableConfigurationProperties({UserConfig.class})      //读取consul中的配置信息,读取到UserConfig
      @EnableTurbine          //Turbine集群监控
      @EnableFeignClients     //启动Feigen
      @EnableHystrix          //启用Hystrix服务降级和熔断
      @EnableHystrixDashboard //启用Hystrix看板
      public class ConsulUserApplication {
      
      
          /**
           * 获取config/application/data下myName的数据
           * 获取config/user/data下myName的数据
           * 获取config/user,dev/data下myName的数据
           * <p>
           * 越往下优先级越高,会覆盖上层的数据
           */
          @Value("${myName}")
          private String myName;
      
          @RequestMapping("/myname")
          public String testHello() {
              System.out.println("my name is : " + myName);
              return myName;
          }
      
      
          /**
           * 获取config/application/data下myName的数据
           * 获取config/user/data下myName的数据
           * 获取config/user,dev/data下myName的数据
           * <p>
           * 越往下优先级越高,会覆盖上层的数据
           */
          @Autowired
          private UserConfig userConfig;
      
          @RequestMapping("/config")
          public String testConfig() {
              System.out.println(userConfig.toString());
              return userConfig.getName();
          }
      
          @LoadBalanced
          @Bean
          /**
           * 用于初始化RestTemplate
           */
          public RestTemplate loadbalancedRestTemplate() {
              return new RestTemplate();
          }
      
          @Autowired
          RestTemplate restTemplate;
      
          /**
           * 通过RestTemplate请求order服务
           *
           * @return
           */
          public String getFirstProduct() {
              return this.restTemplate.getForObject("http://order/", String.class);
          }
      
          /**
           * 验证RestTemplate
           *
           * @return
           */
          @RequestMapping("/getOrderInfo")
          public String getOrderInfo() {
              return getFirstProduct();
          }
      
      
          @Autowired
          private DiscoveryClient discoveryClient;
      
          @RequestMapping("/getOrderInfo1")
          /**
           *可以通过该方法获取order的所有服务
           */
          public String getOrderInfo1() {
              List<ServiceInstance> list = discoveryClient.getInstances("order");
              if (list != null && list.size() > 0) {
                  return list.get(0).getUri().toString();
              }
              return null;
          }
      
          /**
           * 还可以通过Feign来服务间调用
           */
          @FeignClient("order")
          static interface OrderService {
              @RequestMapping("/")
              public String getHelloWord();
      
              @RequestMapping("/getDate")
              public long getDate();
          }
      
      
          @Autowired
          OrderService orderService;
      
          /**
           * 验证Feign
           *
           * @return
           */
          @RequestMapping("/getHelloWord")
          public String getHelloWord() {
              return orderService.getHelloWord();
          }
      
          @RequestMapping("/getDate")
          public long getDate() {
              return orderService.getDate();
          }
      
          /**
           * 用于健康检查,当然可以加入各种权限验证,别人任何人都可以请求
           *
           * @return
           */
          @RequestMapping("/")
          public String home() {
              return "Hello world";
          }
      
          /**
           * 定义hystrix.stream的配置信息
           *
           * @return
           */
          @Bean
          public ServletRegistrationBean<HystrixMetricsStreamServlet> getServlet() {
              HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
              ServletRegistrationBean<HystrixMetricsStreamServlet> registrationBean = new ServletRegistrationBean<HystrixMetricsStreamServlet>(streamServlet);
              registrationBean.setLoadOnStartup(1);
              registrationBean.addUrlMappings("/actuator/hystrix.stream");
              registrationBean.setName("用户服务");
              return registrationBean;
          }
      
          public static void main(String[] args) {
              SpringApplication.run(ConsulUserApplication.class, args);
          }
      }

      参考资料

      https://cloud.spring.io/spring-cloud-consul/reference/html/

      源码:

      https://github.com/wu-gl/springcloud

      截图:

      • Eureka

      创建一个简单的Eureka服务

      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
      </dependency>
      @SpringBootApplication
      @EnableEurekaServer
      public class EurekaServer1Application {
      
          public static void main(String[] args) {
              new SpringApplicationBuilder(EurekaServer1Application.class).run(args);
          }
      }
      server:
        port: 8762
      spring:
        application:
          name: EurekaServer
      eureka:
        instance:
          hostname: localhost
        client:
          registerWithEureka: false  #不需要注册到其他eureka服务
          fetchRegistry: false    #不需要注册到其他eureka服务
          serviceUrl:
            defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/    #这时候无效

      仅此而已

      创建一个高可用的Eureka服务

      server:
        port: 8761
      spring:
        application:
          name: EurekaServer
      eureka:
        instance:
          hostname: localhost
        client:
          serviceUrl:
            defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
      server:
        port: 8762
      spring:
        application:
          name: EurekaServer
      eureka:
        instance:
          hostname: localhost
        client:
          serviceUrl:
            defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/

      服务间彼此互相注册即可,我是一台电脑的运行的,正常port也是一样的。主机ip不同。

      Eureka启用basic认证后,需要处理下跨域

      @SpringBootApplication
      @EnableEurekaServer
      public class EurekaServer1Application extends WebSecurityConfigurerAdapter {
      
          public static void main(String[] args) {
              new SpringApplicationBuilder(EurekaServer1Application.class).run(args);
          }
      
          @Override
          protected void configure(HttpSecurity http) throws Exception {
              // Configure HttpSecurity as needed (e.g. enable http basic).
              http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
              http.csrf().disable();
              //注意:为了可以使用 http://${user}:${password}@${host}:${port}/eureka/ 这种方式登录,所以必须是httpBasic,
              // 如果是form方式,不能使用url格式登录
              http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
          }
      }
      server:
        port: 8762
      spring:
        application:
          name: EurekaServer
        security:
          user:
            name: user
            password: password123
      
      eureka:
        instance:
          hostname: localhost
        client:
          serviceUrl:
            defaultZone: http://user:password123@localhost:8761/eureka/,http://user:password123@localhost:8762/eureka/

      http://${user}:${password}@${ip}:${port}/eureka/

       

      https://cloud.spring.io/spring-cloud-netflix/reference/html/#netflix-hystrix-starter

    • 跟以前变化不大,也被放弃的项目,就不多加介绍了
    •  

      • Spring Cloud Zookeeper

        用于服务发现

      server:
        port: 8081
      
      spring:
        application:
          name: zookeeper-client-user
        cloud:
          zookeeper:
            connect-string: 192.168.3.22:2181
            discovery:
              enabled: true
      @SpringBootApplication
      @RestController
      @EnableDiscoveryClient
      public class ZookeeperOrderApplication {
      
          @RequestMapping("/")
          public String home() {
              return "Hello world";
          }
      
          @RequestMapping("/getDate")
          public long getDate() {
              return System.currentTimeMillis();
          }
      
          public static void main(String[] args) {
              SpringApplication.run(ZookeeperOrderApplication.class, args);
          }
      }

用法比较简单,跟以上比较类似,功能其实也差不多

用于配置中心

同consol类似

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

主要是zookeeper的略有不同

参考资料:https://cloud.spring.io/spring-cloud-zookeeper/reference/html/#activating-2

  • 源码:

https://github.com/wu-gl/springcloud


注意:本文归作者所有,未经作者允许,不得转载

发布了71 篇原创文章 · 获赞 0 · 访问量 4645
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览