springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)

说明

  1. spring cloud alibaba
    • 注册中心 : nacos
    • 配置中心 : nacos
    • 网关 : gateway
    • 负载均衡 : ribbon
    • 远程调用 : openfeign
    • 熔断降级 : sentinel
    • nacos集群配置 : nginx
    • sentinel持久化 : nacos
    • nacos持久化 : mysql
  2. 约定
    • 本工程默认路径 com.yys.springcloud.xxx
    • mvc三层使用包名 controller service dao
    • 实体类使用 entities
  3. 版本
    • springcloud 使用 Hoxton.SR1
    • springcloud alibaba 使用 2.1.0.RELEASE
    • springboot 使用 2.2.2.RELEASE
环境搭建
  1. 创建pom父工程


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>com.yysgroupId>
  <artifactId>cloudalibaba2021artifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>pompackaging>

  <modules>
      <module>cloud-provider-payment8001module>
      <module>cloud-api-commonsmodule>
    <module>cloud-provider-payment8002module>
    <module>cloud-consumer-order81module>
    <module>cloud-gateway-gateway9527module>
  modules>

  
  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <junit.version>4.12junit.version>
    <log4j.version>1.2.17log4j.version>
    <lombok.version>1.16.18lombok.version>
    <mysql.version>5.1.47mysql.version>
    <druid.version>1.1.10druid.version>
    <mybatis.spring.boot.version>1.3.0mybatis.spring.boot.version>
  properties>

  
  <dependencyManagement>
    <dependencies>
      
      <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-dependenciesartifactId>
        <version>2.2.2.RELEASEversion>
        <type>pomtype>
        <scope>importscope>
      dependency>
      
      <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-dependenciesartifactId>
        <version>Hoxton.SR1version>
        <type>pomtype>
        <scope>importscope>
      dependency>
      
      <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-alibaba-dependenciesartifactId>
        <version>2.1.0.RELEASEversion>
        <type>pomtype>
        <scope>importscope>
      dependency>
      <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>${mysql.version}version>
      dependency>
      <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>${druid.version}version>
      dependency>
      <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>${mybatis.spring.boot.version}version>
      dependency>
      <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>${junit.version}version>
      dependency>
      <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>${log4j.version}version>
      dependency>
      <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>${lombok.version}version>
        <optional>trueoptional>
      dependency>
    dependencies>
  dependencyManagement>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-maven-pluginartifactId>
        <configuration>
          <fork>truefork>
          <addResources>trueaddResources>
        configuration>
      plugin>
    plugins>
  build>
project>
  1. 创建cloud-api-commons的module
    module创建方法
    springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第1张图片springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第2张图片
    springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第3张图片添加依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2021artifactId>
        <groupId>com.yysgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>cloud-api-commonsartifactId>

	
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.1.0version>
        dependency>
    dependencies>

project>

创建实体类,包的层次基本就这样后面就不说了
springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第4张图片创建CommonResult

package com.yys.springcloud.entities;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult<T> {
    private Integer code;
    private String message;
    private T data;

    public CommonResult(Integer code,String message){
        this(code,message,null);
    }
}
package com.yys.springcloud.entities;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private Long id;
    private String serial;
}

创建数据库db2021
创建payment表字段id,serial
springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第5张图片
自己手动添加几条记录

服务端工程

同样创建module cloud-provider-payment8001
导入依赖


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloudalibaba2021artifactId>
        <groupId>com.yysgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>cloud-provider-payment8001artifactId>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>

        <dependency>
            <groupId>com.yysgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>${project.version}version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.10version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

project>

编写业务代码
这里就是简单的mvc调用,调用mysql查询一条记录

package com.yys.springcloud.dao;
@Mapper
public interface PaymentDao {
    public int create(Payment payment);
    public Payment getPaymentId(@Param("id") Long id);
}
package com.yys.springcloud.service;

import com.yys.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Param;

public interface PaymentService {
    public int create(Payment payment);
    public Payment getPaymentId(@Param("id") Long id);
}
package com.yys.springcloud.service.impl;
@Service
public class PaymentServiceImpl implements PaymentService {
    @Resource
    private PaymentDao paymentDao;
    @Override
    public int create(Payment payment) {
        return paymentDao.create(payment);
    }
    @Override
    public Payment getPaymentId(Long id) {
        return paymentDao.getPaymentId(id);
    }
}
```java
package com.yys.springcloud.controller;
@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){

        int result = paymentService.create(payment);
        log.info("插入结果" + result);

        if(result > 0){
            return new CommonResult(200,"插入数据库成功" + serverPort,result);
        } else {
            return new CommonResult(444,"插入数据库失败" + serverPort,null);
        }
    }
    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentId(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentId(id);
        log.info("payment:" + payment);
        if(payment != null){
            return new CommonResult(200,"获得数据成功" + serverPort,payment);
        } else {
            return new CommonResult(444,"获得数据失败" + serverPort,null);
        }
    }
}

  • main方法上添加 @EnableDIscoveryClient 开启nacos
package com.yys.springcloud;

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8001.class,args);
    }
}
  • 给dao添加mapper映射(这里用的xml,用注解也可以)


<mapper namespace="com.yys.springcloud.dao.PaymentDao">

    <insert id="create" parameterType="com.yys.springcloud.entities.Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment(serial) values(#{serial});
    insert>

    <select id="getPaymentId" parameterType="long" resultMap="BaseResultMap">
        select * from payment where id = #{id};
    select>

    <resultMap id="BaseResultMap" type="com.yys.springcloud.entities.Payment">
        <id property="id" column="id" jdbcType="BIGINT"/>
        <result property="serial" column="serial" jdbcType="VARCHAR"/>
    resultMap>

mapper>
  • 下面我们来看一下配置文件,配置文件的内容很多我们先配置最简单的其他在后面添加
server:
  port: 8001


spring:
  application:
    name: cloud-nacos-payment
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver             # mysql驱动包
    url: jdbc:mysql://localhost:3306/db2021?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 32194878
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址
mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.springcloud.entities    # 所有Entity别名类所在包
#暴露所有检查点
management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 接着我们采用同样的方式创建module cloud-provider-payment8002 将端口改为8002
客户端工程

创建module cloud-consumer-order81 这里我只创建了一个,可以自己多创建几个
导入依赖


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloudalibaba2021artifactId>
        <groupId>com.yysgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>cloud-consumer-order81artifactId>

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cspgroupId>
            <artifactId>sentinel-datasource-nacosartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        
        <dependency>
            <groupId>com.yysgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>${project.version}version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
project>

编写业务代码
这里是通过service远程调用服务端的服务
这里可以使用ribbon+RestTemplate方式,本项目直接采用了openfeign的方式这种方式是对前一种方式的整合代码简单,统一编写风格

service层

@Component // 记得加到spring容器中
//服务端配置的服务名, 失败会调用PaymentFallbackService.class的同名方法
@FeignClient(value = "cloud-nacos-payment",fallback = PaymentFallbackService.class)
public interface PaymentFeignService {

	//使用feign就可以向调用controller一样远程调用服务
    @GetMapping("/payment/get/{id}")
    CommonResult<Payment> getPaymentId(@PathVariable("id") Long id);
}
//实现PaymentFeignService接口,实现兜底方法
@Component
public class PaymentFallbackService implements PaymentFeignService{
    @Override
    public CommonResult<Payment> getPaymentId(Long id) {
        return new CommonResult<>(444,"远程调用失败,获取不到数据");
    }
}

controller层
这里我们通过service远程调用服务端,id=2我们设置为抛异常来模拟异常情况,为一会熔断降级测试使用

package com.yys.springcloud.controller;

@RestController
@Slf4j
public class OrderController {
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping("/consumer/payment/get/{id}")

    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        if(id == 2){
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }
        return paymentFeignService.getPaymentId(id);
    }
}

  • main方法上添加@EnableFeignClients表示开启feign
//使用nacos
@EnableDiscoveryClient
@SpringBootApplication
//使用feign
@EnableFeignClients
public class OrderMain81 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain81.class, args);
    }
}
  • 配置
server:
  port: 81


spring:
  application:
    name: cloud-nacos-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #nacos集群 使用nginx
        
management:
  endpoints:
    web:
      exposure:
        include: '*'

# 激活Sentinel对Feign的支持
feign:
  sentinel:
    enabled: true
网关配置

创建module cloud-gateway-gateway9527
添加依赖


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloudalibaba2021artifactId>
        <groupId>com.yysgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>cloud-gateway-gateway9527artifactId>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-gatewayartifactId>
        dependency>

        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        
        <dependency>
            <groupId>com.yysgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>${project.version}version>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
project>

添加filter,方式有两个这里我们使用GlobalFilter

@Component
@Slf4j
@Order(0)  //注意添加这个
public class MGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("come in filter --------" + new Date());
		//可以在这里添加过滤规则,这里拦截到的是能匹配的路由路径
        return chain.filter(exchange);
    }
}

添加启动类

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

配置

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: lb://cloud-nacos-consumer #匹配后提供服务的路由地址
          predicates:
            - Path=/consumer/payment/get/**         # 断言,路径相匹配的进行路由
            #- After=2020-02-21T15:51:37.485+08:00[Asia/Shanghai]
            #- Cookie=username,yys
            #- Header=X-Request-Id, \d+  # 请求头要有X-Request-Id属性并且值为整数的正则表达式
    nacos:
      discovery:
        server-addr: localhost:8848
sentinel 熔断降级配置

熔断降级一般配置在客户端,我们在客户端修改配置

  1. 修改配置文件
server:
  port: 81

spring:
  application:
    name: cloud-nacos-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    #添加sentinel配置
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
      
management:
  endpoints:
    web:
      exposure:
        include: '*'

#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://cloud-nacos-payment

# 激活Sentinel对Feign的支持
feign:
  sentinel:
    enabled: true
  1. 在controller上添加控制,打开81工程的controller
package com.yys.springcloud.controller;

@RestController
@Slf4j
public class OrderController {
    @Resource
    private PaymentFeignService paymentFeignService;
    
    @GetMapping("/consumer/payment/get/{id}")
    //这里添加SentinelResource注解,类似hystrix的command方式
    //异常会走fallback方法
    //限流降级等操作走blockHandler方法
    @SentinelResource(value = "getPaymentById",blockHandler = "blockHandler",fallback = "fallbackHandler")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        if(id == 2){
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }
        return paymentFeignService.getPaymentId(id);
    }


    //本例是blockHandler
    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }

    //fallback
    public CommonResult fallbackHandler(@PathVariable  Long id, Throwable e){
        Payment payment = new Payment(id, null);
        return new CommonResult<>(444,"程序错误fallback exception",payment);
    }
}
  1. 下载sentinel的dashboard https://pan.baidu.com/s/1H_InDIiQTrMcYLg1G7ZCmQ 提取码 : 5d8l
    下载好是一个jar包,直接java -jar 启动即可
    访问8080端口,可以看到sentinel监控界面
    账户密码都是 centinel
    springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第6张图片sentinel 是懒加载,当有81端口有请求的时候就会显示监控数据,sentinel具体怎样使用就不提了,可以自行百度
nacos 配置

下载nacos服务端 https://pan.baidu.com/s/1L_syKY8HdiurpOqo0Dx8zg 提取码 : y7xj

运行bin目录下的startup.cmd , 启动后打开8848端口 http://localhost:8848/nacos
账户密码都是nacos

现在运行8527,83,8001,8002服务,当在服务列表中看到这三个服务,说明链接nacos成功
访问 localhost:8011/payment/get/1 说明8001服务可以访问到数据
访问 localhost:81/consumer/payment/get/1 说明81服务可以远程调用到8001服务
访问 localhost:8527/consumer/payment/get/1 说明网关可以路由到81服务

nacos集群

注册中心肯定不能一个,下面我们来使用nginx来进行nacos集群配置
在配置之前先改一下nacos启动脚本,让他可以支持通过参数-p+端口的方式启动

@echo off
rem Copyright 1999-2018 Alibaba Group Holding Ltd.
rem Licensed under the Apache License, Version 2.0 (the "License");
rem you may not use this file except in compliance with the License.
rem You may obtain a copy of the License at
rem
rem      http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.
if not exist "%JAVA_HOME%\bin\java.exe" echo Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! & EXIT /B 1
set "JAVA=%JAVA_HOME%\bin\java.exe"

setlocal enabledelayedexpansion

set BASE_DIR=%~dp0
rem added double quotation marks to avoid the issue caused by the folder names containing spaces.
rem removed the last 5 chars(which means \bin\) to get the base DIR.
set BASE_DIR="%BASE_DIR:~0,-5%"

set DEFAULT_SEARCH_LOCATIONS="classpath:/,classpath:/config/,file:./,file:./config/"
set CUSTOM_SEARCH_LOCATIONS=%DEFAULT_SEARCH_LOCATIONS%,file:%BASE_DIR%/conf/

set MODE="standalone"
set FUNCTION_MODE="all"
set SERVER=nacos-server
set PORT=8848
set MODE_INDEX=-1
set FUNCTION_MODE_INDEX=-1

# 我们仿照原来的样子自己写一个参数配置   ---- 额不知道他的注释是什么,使用的时候此行删掉
set SERVER_INDEX=-1
set PORT_INDEX=-1


set i=0
for %%a in (%*) do (
   if "%%a" == "-m" ( set /a MODE_INDEX=!i!+1 )
   if "%%a" == "-f" ( set /a FUNCTION_MODE_INDEX=!i!+1 )
   if "%%a" == "-s" ( set /a SERVER_INDEX=!i!+1 )
   if "%%a" == "-p" ( set /a PORT_INDEX=!i!+1 )
   set /a i+=1
)

set i=0
for %%a in (%*) do (
   if %MODE_INDEX% == !i! ( set MODE="%%a" )
   if %FUNCTION_MODE_INDEX% == !i! ( set FUNCTION_MODE="%%a" )
   if %SERVER_INDEX% == !i! (set SERVER="%%a")
   if %PORT_INDEX% == !i! (set PORT="%%a")
   set /a i+=1
)

if %MODE% == "standalone" (
    set "JAVA_OPT=%JAVA_OPT% -Xms512m -Xmx512m -Xmn256m"
    set "JAVA_OPT=%JAVA_OPT% -Dnacos.standalone=true"
) else (
    set "JAVA_OPT=%JAVA_OPT% -server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m"
    set "JAVA_OPT=%JAVA_OPT% -XX:-OmitStackTraceInFastThrow XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=%BASE_DIR%\logs\java_heapdump.hprof"
    set "JAVA_OPT=%JAVA_OPT% -XX:-UseLargePages"
)

if %FUNCTION_MODE% == "config" (
  set "JAVA_OPT=%JAVA_OPT% -Dnacos.functionMode=config"
)
if %FUNCTION_MODE% == "naming" (
  set "JAVA_OPT=%JAVA_OPT% -Dnacos.functionMode=naming"
)


set "JAVA_OPT=%JAVA_OPT% -Xbootclasspath/a:%BASE_DIR%\plugins\cmdb:%BASE_DIR%\plugins\mysql"
set "JAVA_OPT=%JAVA_OPT% -Dnacos.home=%BASE_DIR%"
set "JAVA_OPT=%JAVA_OPT% -Dloader.path=%BASE_DIR%/plugins/health -jar %BASE_DIR%\target\%SERVER%.jar"
set "JAVA_OPT=%JAVA_OPT% --spring.config.location=%CUSTOM_SEARCH_LOCATIONS%"
set "JAVA_OPT=%JAVA_OPT% --logging.config=%BASE_DIR%/conf/nacos-logback.xml"

# 这里最后会调用java运行所以我们添加虚拟机参数 -Dserver.port = %PORT% 即可   ps此行删掉
call "%JAVA%" -Dserver.port=%PORT% %JAVA_OPT% nacos.nacos %*

接下来配置nginx,nginx配置比较简单就配置路由到三个nacos端口就行了,nginx会默认轮询


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
	
    upstream cluster{
    	server 127.0.0.1:3333;
    	server 127.0.0.1:4444;
    	server 127.0.0.1:5555;
    }

    server{
    	listen	1111;
    	server_name	 localhost;

    	location / {
    		proxy_pass http://cluster;
    	}
    }
}

再打开nacos里conf目录下cluster.conf,配置集群

192.168.1.107:3333
192.168.1.107:4444
192.168.1.107:5555

上面配置好了就可以使用 startup.cmd -p 3333 startup.cmd -p 4444 … 集群启动即可
开启nginx 现在nginx 监听1111端口
我们将项目中所有的8848端口改为1111端口

spring:
  cloud:
    nacos:
      discovery:
        server-addr: localhost:1111 #nacos集群 使用nginx
nacos持久化

集群配置会产生问题,因为nacos默认会保存数据到文件中,这样每一个nacos都会保存一份,数据就不同步了,我们可以通过配置让nacos将数据保存到mysql中

进入conf下打开application.properties,里面添加代码

spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=32194878

文件夹中有一个nacos-mysql.sql的sql文件创建一个nacos_config的库执行他

这样nacos的持久化就配置好了

配置中心设置

nacos也可以作为配置中心使用,这里我们将数据库连接的配置放到配置中心让8001/8002服务来从配置中心读取配置文件
springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第7张图片

  • 可以给配置文件分组,添加命名空间,这里就不展开了,我们只使用默认配置
    springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第8张图片
    下面找到8001服务,新建配置文件 bootstrap.yml ,将application.yml的配置全部放到这个里面
server:
  port: 8001


spring:
  application:
    name: cloud-nacos-payment
  #这里内容从nacos配置中心读取
  #配置起名规则# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
  #cloud-nacos-payment-dev.yaml  (这里要用yaml)
#  datasource:
#    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
#    driver-class-name: org.gjt.mm.mysql.Driver             # mysql驱动包
#    url: jdbc:mysql://localhost:3306/db2021?useUnicode=true&characterEncoding=utf-8&useSSL=false
#    username: root
#    password: 32194878
  cloud:
    nacos:
      discovery:
        server-addr: localhost:1111  #nginx代理nacos集群
#        server-addr: localhost:8848 #配置Nacos地址
      config:
        server-addr: localhost:1111 #Nacos作为配置中心地址
        file-extension: yaml #指定yaml格式的配置

mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.atguigu.springcloud.entities    # 所有Entity别名类所在包


management:
  endpoints:
    web:
      exposure:
        include: '*'

将原来的application.yml改为

spring:
  profiles:
    active: dev # 表示开发环境
    #active: test # 表示测试环境

将上面那段注释内容放到配置中心中
dataId 规则
${spring.application.name}- ${spring.profile.active}. ${spring.cloud.nacos.config.file-extension}
cloud-nacos-payment-dev.yaml (注意这里要用yaml)
springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第9张图片点击发布,运行8001,若没有报错说明读取成功

sentinel持久化

我们在使用sentinel 的时候会发现sentinel在服务重启之后配置的降级熔断等规则就没有了,我们可以考虑将规则写入到nacos的配置中心中,每次启动从nacos取
sentinel已经帮我们整合好了,我们只需要导入依赖更改配置即可,现在我们给81服务添加持久化
记得导入依赖

<dependency>
	<groupId>com.alibaba.cspgroupId>
    <artifactId>sentinel-datasource-nacosartifactId>
dependency>

更改配置

spring:
  application:
    name: cloud-nacos-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:1111 #nacos集群 使用nginx
#        server-addr: localhost:8848 #nacos集群 使用nginx
    sentinel:
      transport:
        #配置Sentinel dashboard地址
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
       ###############################看这里看这里 
      #持久化sentinel规则从配置中心取一个 叫 cloud-nacos-consumer的json文件
      datasource:
        ds1:
          nacos:
            server-addr: localhost:1111
            dataId: cloud-nacos-consumer
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow

现在我们在nacos添加cloud-nacos-consumer配置
这些配置可以从官方文档中找到
springcloud alibaba一键部署攻略(nacos集群+sentinel+openfeign+gateway)_第10张图片启动81服务没有报错说明配置成功

最后我们来梳理一下启动运行流程

  1. 启动nginx
  2. 启动端口为3333,4444,5555的nacos
  3. 启动8001/8002服务
  4. 启动81服务
  5. 启动sentinel的dashboard
  6. 启动9527网关
  7. 配置sentinel降级限流等规则
  8. 访问 localhost:8001/payment/get/1 测试
  9. 访问 localhost:81/consumer/payment/get/1 测试
  10. 访问 localhost:9527/consumer/payment/get/1 测试
  11. 进行压力测试,测试熔断降级规则是否生效

你可能感兴趣的:(cloud,spring,boot,spring,cloud,spring,cloud,alibaba,spring)