SpringCloud学习笔记

5 篇文章 0 订阅

##Ribbon
Ribbon被restTemplate进行调用,并负责客户端负载均衡.
比如同一个微服务可以启动两个,Ribbon会从注册中心获得这个信息,然后Ribbon会自己决定调用哪个.

实现这个客户端类

package com.aihidao.sc.client;
 
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
 
import com.aihidao.sc.pojo.Product;
 
@Component
public class ProductClientRibbon {
 
    @Autowired
    RestTemplate restTemplate;
 
    public List<Product> listProdcuts() {
        return restTemplate.getForObject("http://PRODUCT-DATA-SERVICE/products",List.class);
    }
 
}

####RestTemplate
那么关于 RestTemplate 则在启动类种实现,代码如下

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ProductViewServiceRibbonApplication {
 
    public static void main(String[] args) {
        int port = 0;
       		final int defaultPort = 8010;
		Future<Integer> future = ThreadUtil.execAsync(new Callable() {
			public Object call() {
				int p = 0;
				System.out.println("请于5秒钟内输入端口号, 推荐  8010  超过5秒将默认使用 " + defaultPort);
                Scanner scanner = new Scanner(System.in);
                while(true) {
                    String strPort = scanner.nextLine();
                    if(!NumberUtil.isInteger(strPort)) {
                        System.err.println("只能是数字");
                        continue;
                    }
                    else {
                        p = Convert.toInt(strPort);
                        scanner.close();
                        break;
                    }
                }
				return p;
			}
		});
		
		try {
			port = future.get(5, TimeUnit.SECONDS);
		}catch(TimeoutException e) {
			port = defaultPort;
		}catch (ExecutionException e) {
			port = defaultPort;
		} catch (InterruptedException e) {
			port = defaultPort;
		} 
        if(!NetUtil.isUsableLocalPort(port)) {
            System.err.printf("port %d has been occupied,can't start!%n", port );
            System.exit(1);
        }
        new SpringApplicationBuilder(ProductViewServiceRibbonApplication.class).properties("server.port=" + port).run(args);
 
    }
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
     
}

####Feign
Feign为Ribbon的一个封装类,为的就是让Ribbon调用起来更方便将ProductClientRibbon类改为一下方式即可

  <dependency>
  	<groupId>org.springframework.cloud</groupId>
  	<artifactId>spring-cloud-starter-openfeign</artifactId>
  </dependency>
@FeignClient(value = "PRODUCT-DATA-SERVICE")
public interface ProductClientFeign {
	@GetMapping("/products")
	public List<Product> listProducts();
}

剩下的修改之前做的Ribbon相关类,改为Feign类
启动方法里的
RestTemplate restTemplate() 方法也可以注释掉.

##服务链路追踪
包引入

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

还需要一个jar包(zipkin-server-2.10.1-exec)服务器需要启动.
需要在各个为微服务里的启动类里加入sampler[采集器]方法

@Bean
public Sampler defaultSampler() {
	return Sampler.ALWAYS_SAMPLE;
}

在application.yml中配置zipkin地址。

zipkin:
   base-url: http://localhost:9411

##服务器读取配置【config】
config分客户端和服务端
###config服务端
1、依赖

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

2、添加注释 EnableConfigServer

@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
@EnableEurekaClient
public class ConfigServerApplication {
    public static void main(String[] args) {
        int port = 8030;
        if(!NetUtil.isUsableLocalPort(port)) {
            System.err.printf("端口%d被占用了,无法启动%n", port );
            System.exit(1);
        }
        new SpringApplicationBuilder(ConfigServerApplication.class).properties("server.port=" + port).run(args);
    }
}

3 application.yml配置

spring:
  application:
    name: config-server
  cloud:
    config:
      label: master
      server:
        git:
          uri: https://github.com/aihidao/Demo_SpringClodConfig/
          searchPaths: respo
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

###config客户端配置
这次教程里将config 写入了 bootstrap.yml 里,
最基本的区别就是bootstrap.yml比application.yml最先配置。

所以我们在bootstrap.yml里加代码[注意我们把client代码移入这里]

//bootstrap.yml
spring:
   cloud:
      config:
         label: master
         profile: dev
         discovery:
            enabled: true
            serviceId: config-server  
   client:
      serviceUrl:
         defaultZone: http://localhost:8761/eureka/
//application.uml
spring:
   application:
      name: product-view-service-feign
   zipkin:
      base-url: http://localhost:9411
   thymeleaf:
      catche: false
      prefix: classpath:/templates/
      suffix: .html
      encoding: UTF-8
      content-type: text/html
      mode: HTML555

我们把之前的feign的主方法改为 config client.
首先 在启动类里加入 默认Sampler

	@Bean
	public Sampler defaultSampler() {
		return Sampler.ALWAYS_SAMPLE;
	}

重要:当客户端启动的时候如何找到自己的配置文件呢?
首先搜索目录为服务器配置的文件目录.
我们可以看到 label = master 则是在 master分支里找
是 该配置客户端的 名字 [product-view-service-feign] + profile名字, 这里配置的profile为 dev 则名字为 product-view-service-feign-dev
然后 全名就为 product-view-service-feign-dev.properties
服务器应该是提前 遍历了整个文件夹以及里面的属性文件.所以 这时候就有了属性值 version
如果 config客户端需要调用则使用一下代码进行赋值

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

全部代码


@Controller
//RefreshScope 待研究
@RefreshScope
public class ProductController {
	@Autowired
	ProductService productService;
    @Value("${version}")
	String version;
	@RequestMapping("/products")
	public Object products(Model m) {
		List<Product> ps = productService.listProduct();
		m.addAttribute("ps", ps);
		m.addAttribute("version", version);
		return "products";
	}
}

//以上属性加载方式是自己猜测,待研究.
##消息总线
###actuator
actuator还不太理解,目前理解 这个插件为 显示服务器状态吧.
官方解释
Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application.

一般访问时候在链接后加上 http://***.***/actuator/***

最后的*好代表需要监视或者管理的功能.
我们在加入消息总线后 通过访问 bus-refresh来刷新消息.
然后再通过RabbitMQ来通知其他应用,配置的改变

加入配置

//actor
org.springframework.boot
spring-boot-starter-actuator
//消息总线 我们这里使用RabbitMQ
org.springframework.cloud
spring-cloud-starter-bus-amqp

启动bus 目前还不明白 bs-amqp 是针对 RabbitMQ 还是 可以选择消息队列插件类型. 先记录下来以后研究.

bootstrap.yml
spring:
   cloud:
      config:
         label: master
         profile: dev
         discovery:
            enabled: true
            serviceId: config-server
		#start
      bus:
         enabled: true
         trace:
            enabled: true
   client:
      serviceUrl:
         defaultZone: http://localhost:8761/eureka/
#rabbitmq
rabbitmq:
   host: localhost
   port: 15672
   username: guest
   password: guest

接下来是 允许访问 bus-refresh , 这个也是待研究. 总之是用来允许访问 bus-refresh的
这个配置是允许访问所有.

management:
  endpoints:
    web:
      exposure:
        include: "*"
      cors:
        allowed-origins: "*"
        allowed-methods: "*"

一旦配置更新 则使用post方式访问 http://localhost:8010/actuator/bus-refresh[localhost:8010是相关springboot服务地址]

##断路器[Hystrix]
断路器,就是当发现提供远程数据的springboot 无法访问或者挂掉的时候,就断掉之前的路线.然后自己处理这些数据.不然一旦报错,就会显得页面特别不友好.

老例子第一步 加入插件

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

修改之前Feign中的 @FeignClient注释即可

//将
@FeignClient(value = "PRODUCT-DATA-SERVICE")
//改为
@FeignClient(value = "PRODUCT-DATA-SERVICE",fallback = ProductClientFeignHystrix.class)

fallback 后面跟随的是如果发生无法访问,那么将由哪个类来处理.
所以这个时候我们要创建这个类

@Component
public class ProductClientFeignHystrix {
	public List<Product> listProducts(){
        List<Product> result = new ArrayList<Product>();
        result.add(new Product(0,"产品数据微服务不可用",0));
        return result;
	}
}

然后在application.yml中启用

feign.hystrix.enabled: true

###dashboard配置

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>   

微服务 类 要加注释

@EnableHystrixDashboard

监视对象 家注释

@EnableCircuitBreaker

配置文件

spring:
  application:
    name: hystrix-dashboard

配置完成后启动环境 访问
http://localhost:8010/actuator/hystrix.stream

###断路器聚合[turbine]
依赖

org.springframework.cloud
spring-cloud-starter-netflix-turbine

微服务注释

@EnableTurbine

application.yml

spring:
  application.name: turbine
turbine:
  #aggregator待研究
  aggregator:
    clusterConfig: default
  appConfig: product-view-service-feign  ### 配置Eureka中的serviceId列表,表明监控哪些服务
    #clusterNameExpression待研究
  clusterNameExpression: new String("default")
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

##网关[Zuul]
依赖

org.springframework.cloud
spring-cloud-starter-netflix-zuul

注释

@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableDiscoveryClient

配置

zuul:
  routes:
    api-a:
	  #配置后该服务的服务路径为 域名 + zuul端口 + /api-data/ + MappingName
      path: /api-data/**
      serviceId: PRODUCT-DATA-SERVICE
    api-b:
      path: /api-view/**
      serviceId: PRODUCT-VIEW-SERVICE-FEIGN
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值