线程、数据库、算法、JVM、分布式、微服务、框架、Spring相关知识
一线互联网P7面试集锦+各种大厂面试集锦
学习笔记以及面试真题解析
创建consul-user-service模块和consul-ribbon-service模块;
修改相关依赖,把原来的Eureka注册发现的依赖改为Consul的,并添加SpringBoot Actuator的依赖:
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-consul-discovery
修改配置文件application.yml,将Eureka的注册发现配置改为Consul的:
server:
port: 8206
spring:
application:
name: consul-user-service
cloud:
consul:
将服务注册到consul
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
运行两个consul-user-service和一个consul-ribbon-service,在Consul页面上可以看到如下信息:
负载均衡功能
由于我们运行了两个consul-user-service,而consul-ribbon-service默认会去调用它的接口,我们调用consul-ribbon-service的接口来演示下负载均衡功能。
多次调用接口:http://localhost:8308/user/1 ,可以发现两个consul-user-service的控制台交替打印如下信息。
2019-12-29 18:20:47.834 INFO 10460 — [io-8207-exec-10] c.j.s.controller.UserController : 根据id获取用户信息,用户名称为:jourwon
我们通过创建consul-config-client模块,并在Consul中添加配置信息来演示下配置管理的功能。
创建consul-config-client模块
在pom.xml中添加相关依赖:
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-consul-config
org.springframework.cloud
spring-cloud-starter-consul-discovery
org.springframework.boot
spring-boot-starter-actuator
添加配置文件application.yml,启用的是dev环境的配置:
spring:
profiles:
active: dev
添加配置文件bootstrap.yml,主要是对Consul的配置功能进行配置:
server:
port: 9101
spring:
application:
name: consul-config-client
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: consul-config-client
config:
是否启用配置中心功能
enabled: true
设置配置值的格式
format: yaml
设置配置所在目录
prefix: config
设置配置的分隔符
profile-separator: ‘:’
配置key的名字,由于Consul是K/V存储,配置存储在对应K的V中
data-key: data
创建ConfigClientController,从Consul配置中心中获取配置信息:
@RefreshScope
@RestController
public class ConfigClientController {
@Value(“${config.info}”)
private String configInfo;
@GetMapping(“/configInfo”)
public String getConfigInfo() {
return configInfo;
}
}
在Consul中添加配置
在consul中添加配置存储的key为:
config/consul-config-client:dev/data
在consul中添加配置存储的value为:
config:
info: “config info for dev”
存储信息截图如下:
启动consul-config-client,调用接口查看配置信息:http://localhost:9101/configInfo
config info for dev
Consul的动态刷新配置
我们只要修改下Consul中的配置信息,再次调用查看配置的接口,就会发现配置已经刷新。回想下在使用Spring Cloud Config的时候,我们需要调用接口,通过Spring Cloud Bus才能刷新配置。Consul使用其自带的Control Bus 实现了一种事件传递机制,从而实现了动态刷新功能。
本次面试答案,以及收集到的大厂必问面试题分享:
g Cloud Bus才能刷新配置。Consul使用其自带的Control Bus 实现了一种事件传递机制,从而实现了动态刷新功能。
本次面试答案,以及收集到的大厂必问面试题分享:
[外链图片转存中…(img-FLlIKOph-1715412633384)]