文章目录
nacos
简介
-
为什么叫Nacos:前四个字母分别为Naming和Configuration的前两个字母,最后的s为Service。
-
是什么:一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。
-
Nacos: Dynamic Naming and Configuration Service
Nacos就是注册中心+配置中心的组合 -> Nacos = Eureka+Config+Bus -
能干嘛
替代Eureka做服务注册中心
替代Config做服务配置中心 -
下载:https://github.com/alibaba/nacos/releases
文档:https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html
配置
父pom
<dependencyManagement>
<dependencies>
<!--spring cloud alibaba 2.2.6.RELEASE-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<!-- <version>2.2.6.RELEASE</version> -->
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
pom
- 服务发现
<!--SpringCloud ailibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
- 配置中心
<!--nacos-config-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
yaml
注意:每个服务必须指定名字!否则无法服务发现
- bootstrap.yml
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacos服务注册中心地址
config:
server-addr: localhost:8848 #Nacos作为配置中心地址
file-extension: yaml #指定yaml格式的配置
group: DEV_GROUP
namespace: 7d8f0f5a-6a53-4785-9686-dd460158e5d4 #命名空间
- application.yml
spring:
profiles:
active: dev # 表示开发环境
#active: test # 表示测试环境
#active: info
以上配置解释:
在 Nacos Spring Cloud中,dataId的完整格式如下:
${prefix}-${spring-profile.active}.${file-extension}
其中:
prefix
默认为spring.application.name的值,也可以通过配置项spring.cloud.nacos.config.prefix来配置。spring.profile.active
即为当前环境对应的 profile。注意:当spring.profile.active为空时,对应的连接符 - 也将不存在,datald 的拼接格式变成${prefix}.${file-extension}file-exetension
为配置内容的数据格式,可以通过配置项spring .cloud.nacos.config.file-extension来配置。目前只支持properties和yaml类型。最后公式:
${spring.application.name)}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
例如上面的配置:应用名-dev.yaml
main
@EnableDiscoveryClient
不加这个也可以
@RefreshScope
- @Value需要动态获取值,要加Spring Cloud 原生注解
@RefreshScope
实现配置自动更新。
- 需要动态获取值的地方加
@RefreshScope
注解
- nacos的初始配置:
启动项目,访问,取到的值:
- 不重启项目的情况下修改nacos的配置:
再次访问,发现取到的数据也改变了:(必须加@RefreshScope
注解)
持久化
- 安装数据库,版本要求:5.6.5+
- 初始化mysq数据库,数据库初始化文件: nacos-mysql.sql
- 修改conf/application.properties文件(增加支持mysql数据源配置(目前只支持mysql),添加mysql数据源的url、用户名和密码):
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos_devtest?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=nacos_devtest
db.password=youdontknow
使用
- 新建命名空间,添加如下配置,并把原来在
application.yaml
中的内容分别写到以下文件中:
注:我的命名空间id可以自定义:而不是uuid
- 配置
bootstrap.yaml
:
spring:
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
namespace: coupon #写命名空间ID
extension-configs:
- dataid: datasource.yaml
refresh: true
group: dev
- dataid: mybatis.yaml
refresh: true
group: dev
- dataid: other.yaml
refresh: true
group: dev
启动时候的部分日志:读取了上面配置的文件
附
- nacos做配置中心
feign
面向接口编程
配置
pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
main
@EnableFeignClients
service
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")//微服务的服务名
public interface PaymentFeignService{
//对应微服务的controller中包含的方法
}
超时
- 解决方法:在yaml中配置如下内容:(时间自己看着改,例如,read time out,就把readTimeout时间改大一些)
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
hystrix:
enabled: true
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 60000
- 参考于官网:https://docs.spring.io/spring-cloud-openfeign/docs/2.2.10.RELEASE/reference/html/#timeout-handling
英语水平有限,翻译一下:
使用
两个微服务使用的对象可以不一致:
远程调用未携带Cookie等参数问题
发现Feign直接新建一个请求
这个新请求没有headers信息:
继续往下看,有这么一个方法:
它遍历了该类的所有拦截器对请求进行处理,默认拦截器是个空的List
拦截器的类型是:
我们可以自定义一个拦截器处理我们自己的请求,使其加上Cookie,例如:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @program: gulimall
* @description: feign拦截器
* @author: liangjiayy
* @create: 2022-06-22 10:26
**/
@Configuration
public class MyFeignRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
String cookie = ((ServletRequestAttributes) requestAttributes).getRequest().getHeader("Cookie");
template.header("Cookie",cookie);
}
}
其中,RequestContextHolder.getRequestAttributes()主要利用ThreadLocal实现,当前线程共享,可以获取到当前请求信息
这样,会自动为我们加上Cookie信息,如图:
如果RequestContextHolder.getRequestAttributes()
获取到的为null,可在拦截器(HandlerInterceptor的preHandle()
方法)加入以下代码:
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(requestAttributes,true);
gateway
官网: https://docs.spring.io/spring-cloud-gateway/docs/2.2.9.RELEASE/reference/html/
三大核心概念
- Route(路由) - 路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由;
- Predicate(断言) - 参考的是Java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由;查看可配置的断言
- Filter(过滤) - 指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。查看可配置的过滤器
配置
pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
yml配置样例
spring:
cloud:
gateway:
routes:
- id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
#uri: lb://cloud-payment-service #匹配后提供服务的路由地址
predicates:
- Path=/payment/get/** # 断言,路径相匹配的进行路由
- id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
#uri: lb://cloud-payment-service #匹配后提供服务的路由地址
predicates:
- Path=/payment/lb/** # 断言,路径相匹配的进行路由
*配置方式2:
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GateWayConfig
{
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder)
{
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
routes.route("path_route_atguigu",
r -> r.path("/guonei")
.uri("http://news.baidu.com/guonei")).build();
return routes.build();
}
}
配置说明
After
- After=2017-01-20T17:42:47.789-07:00[America/Denver]
在某个时间之后的请求才会被转发
Before
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
在某个时间之前的请求才会被转发
Between
- Between=2017-01-20T17:42:47.789-07:00[America/Denver],2017-01-21T17:42:47.789-07:00[America/Denver]
在某个时间段之间的才会被转发
Cookie
- Cookie=mycookie,mycookievalue
cookie中包含mycookie=mycookievalue
Path
- Path=/gate/,/rule/
当请求的路径为gate、rule开头的时,转发到http://localhost:9023服务器上
Header
- Header=X-Request-Id, \d+
携带参数X-Request-Id且满足\d+正则表达式的请求头才会匹配
Host
- Host=**.somehost.org,**.anotherhost.org
www.somehost.org 、beta.somehost.org 、www.anotherhost.org.都可以被匹配到
Method
- Method=GET,POST
get、put请求都可以访问
Path
- Path=/red/{segment},/blue/{segment}
/red/1 、/red/blue 、 /blue/green都可以
Query
- Query=red, gree
请求参数中包含red=gree键值对,例如:http://xx?red=gree
RemoteAddr
- RemoteAddr=192.168.1.1/24
IP地址或IP段
Weight
spring:
cloud:
gateway:
routes:
- id: weight_high
uri: https://weighthigh.org
predicates:
- Weight=group1, 8
- id: weight_low
uri: https://weightlow.org
predicates:
- Weight=group1, 2
80%概率去访问 weighthigh.org , 20%概率去访问 weighlow.org
路径改写之RewritePath
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: https://example.org
predicates:
- Path=/red/**
filters:
- RewritePath=/red(?<segment>/?.*), $\{segment}
访问 /red/blue 会跳转到 /blue
附录
IDEA中设置Run Dashboard
在另一篇文章中:https://blog.csdn.net/m0_55155505/article/details/124164365
设置最大运行内存
-Xmx用来设置你的应用程序(不是JVM)能够使用的最大内存数:
虚拟机选项中设置:-Xmx100m
, 表示最多只能用100M
批量启动微服务:
- 编辑配置
- 点
+
, 找到compound
- 通过
+
来添加需要批量启动的配置,写上名称,应用即可