<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>
<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>
创建实体类,包的层次基本就这样后面就不说了
创建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
自己手动添加几条记录
同样创建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);
}
}
}
package com.yys.springcloud;
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class,args);
}
}
<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-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);
}
}
//使用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
熔断降级一般配置在客户端,我们在客户端修改配置
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
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);
}
}
下载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服务
注册中心肯定不能一个,下面我们来使用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将数据保存到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服务来从配置中心读取配置文件
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)
点击发布,运行8001,若没有报错说明读取成功
我们在使用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配置
这些配置可以从官方文档中找到
启动81服务没有报错说明配置成功
最后我们来梳理一下启动运行流程