分类目录编程

Vue中使用excel导出

<!-- 导入需要的包 (一定要放到head标签里)-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.1/xlsx.full.min.js"></script>

cnpm install -S file-saver xlsx

import FileSaver from “file-saver”;
import XLSX from “xlsx”;

table标签el-table上加一个id:如outTable,对应下面的exportExcel方法中的 document.querySelector(‘#outTable‘)

exportExcel() {
      var xlsxParam = { raw: true };//转换成excel时,使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
          "sheetjs.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

Sequelize

npm install mysql2 -s
npm -install sequelize -d
npm -install sequelize-cli -d

创建一个数据库
sequelize cli
npx sequelize init

生成模型文件
– migrate
– model
npx sequelize model:generate --name Todo --attribbutes name:string,deadline:date

持久化数据
npx sequelize db:migrate

nvm 管理 nodejs 版本

安装见github
nstall & Update Script

To install or update nvm, you should run the install script. To do that, you may either download and run the script manually, or use the following cURL or Wget command:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
Running either of the above commands downloads a script and runs it. The script clones the nvm repository to ~/.nvm, and attempts to add the source lines from the snippet below to the correct profile file (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc).

export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
  • 显示nodejs已安装版本
    nvm ls
  • 当前node版本
    nvm current
  • 显示远程的lts版本
    nvm ls-remote –lts
  • 安装指定版本
    nvm install vx.x.x
  • 当前环境使用指定版本
    nvm use vx.x.x
  • 长期使用指定版本
    nvm alias default vx.x.x

Vue 项目中使用 echarts

官网

第一种方法,直接引入echarts
安装echarts项目依赖
npm install echarts –save

//或者
npm install echarts -S

//var echarts = require(‘echarts’); //单个引用

全局引入
我们安装完成之后,可以在 main.js 中全局引入 echarts
import echarts from “echarts”;
Vue.prototype.$echarts = echarts;

创建图表
<template>
  <div id="app">
    <div id="main" style="width: 600px;height:400px;"></div>
  </div>
</template>
<script>
export default {
  name: "app",
  methods: {
    drawChart() {
      // 基于准备好的dom,初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("main"));
      // 指定图表的配置项和数据
      let option = {
        title: {
          text: "ECharts 入门示例"
        },
        tooltip: {},
        legend: {
          data: ["销量"]
        },
        xAxis: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        },
        yAxis: {},
        series: [
          {
            name: "销量",
            type: "bar",
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    }
  },
  mounted() {
    this.drawChart();
  }
};
</script>
问题:
在以上例子中,我们获取dom的方式是通过document.getElementById('main'),也就是元素的id获取到dom的,这其实是会出现问题的。
代码如下
<div id="main"></div>
this.$echarts.init(document.getElementById('main'))
因为vue是单页面应用,如果将以上的组件使用两次,一个页面内id是不允许相同的,就会出现第一个组件正常显示,第二个组件无法显示。
解决办法:
在vue中,我们可以通过另一种方式获取dom,vue有一个$refs的对象,只要将组件注册ref。
代码如下
<div ref="main"></div>
this.$echarts.init(this.$refs.main)
或
this.$echarts.init(this.$refs['main'])
通过以上方法获取dom,无论组件复用多少次,都不需要担心id唯一的问题了。

第二种方法,使用 Vue-ECharts 组件
安装组件
npm install vue-echarts -S

使用组件
<template>
  <div id="app">
    <v-chart class="my-chart" :options="bar"/>
  </div>
</template>
<script>
import ECharts from "vue-echarts/components/ECharts";
import "echarts/lib/chart/bar";
//按需引入
import "echarts/lib/chart/line";
import "echarts/lib/chart/pie";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/legend";
import "echarts/lib/component/markPoint";
import "echarts/lib/component/markLine";
import "echarts/lib/component/graphic";

export default {
  name: "App",
  components: {
    "v-chart": ECharts
  },
  data: function() {
    return {
      bar: {
        title: {
          text: "ECharts 入门示例"
        },
        tooltip: {},
        legend: {
          data: ["销量"]
        },
        xAxis: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        },
        yAxis: {},
        series: [
          {
            name: "销量",
            type: "bar",
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      }
    };
  }
};
</script>
<style>
.my-chart {
  width: 800px;
  height: 500px;
}
</style>
用 npm 与 Vue Loader 基于 ES Module 引入(推荐用法)用 npm 与 Vue Loader 基于 ES Module 引入(推荐用法)

import Vue from ‘vue’
import ECharts from ‘vue-echarts’ // 在 webpack 环境下指向 components/ECharts.vue

// 手动引入 ECharts 各模块来减小打包体积
import ‘echarts/lib/chart/bar’
import ‘echarts/lib/component/tooltip’

// 如果需要配合 ECharts 扩展使用,只需要直接引入扩展包即可
// 以 ECharts-GL 为例:
// 需要安装依赖:npm install –save echarts-gl,并添加如下引用
import ‘echarts-gl’

// 注册组件后即可使用
Vue.component(‘v-chart’, ECharts)

图表主题颜色的修改
echarts中有三种常见主题类型: default, light, dark,读者没有太大的颜色要求的话,可以直接修改theme。
示例如下:

<v-chart :options="barOptions" autoresize theme="light"></v-chart>
柱状图颜色的修改可以在options参数中直接添加color数组,如下示例:
options:{
    ...
    color: ["#64CDF0", "#F5686F"],
    ...
}
另外可参考官方示例,直接添加theme.json文件。
`````
2.XY轴体颜色和文本颜色修改
x轴的样式修改可以在xAxis配置参数中进行设置,y轴在yAxis中进行配置,可以修改轴线的颜色,文本的颜色大小,图标内分割线的颜色等

options: {

xAxis: [
{
type: “category”,
data: [“1月”,”2月”,”3月”,”4月”,”5月”,”6月”,”7月”,”8月”,”9月”,”10月”,”11月”,”12月”],
// 修改文本的颜色
axisLabel: {
color: “#BB3137”,
fontSize: 10
},
// 修改轴线的颜色
axisLine: {
lineStyle: {
color: “#BB3137”
}
}
}
],
yAxis: [
{
type: “value”,
axisLabel: {
color: “#BB3137”,
fontSize: 10
},
// 修改y轴横向分割线的颜色
splitLine: {
lineStyle: {
color: [“#FFC9CB”]
}
},
axisLine: {
lineStyle: {
color: “#BB3137”
}
}
}
],

}

横向柱状图的显示
在配置xAxis和yAxis的时候,第一个参数就是type,这个参数用于说明该轴的类型,当x的type为value,y的type为category的时候,柱状图就会显示成横向柱状图。
过滤xy轴文本内容
上图二中,如果没有做任何处理,x轴会显示20000,40000…这种类型,这样显示内容较长,不太友好,那么怎么改成上述那种显示呢?
xy轴文本的配置项中,都有formatter这一配置项,直接在这里进行修改就可以,示例如下:

xAxis: [
{
type: “value”,
axisLabel: {
fontSize: 10,
formatter: function(value, index) {
return parseInt(value / 10000) + “万”;
}
}
}
],

Y轴文本显示在轴线内
刻度标签默认是显示在刻度线左侧,如果想要显示在右侧,需要将inside设置为true即可,当进行此设置后,刻度标签可能会被柱状图覆盖掉,这时候,还需要设置zlevel,示例如下:
        inverse: true,
        axisLabel: {
          fontSize: 10,
          inside: true,
          interval: 0
        },
        zlevel: 1
inverse是用来显示是否翻转刻度线上的内容,即默认从上往下是321显示,如果你不想这样显示,将inverse设为true,就会按照123方式显示。
6.在柱状条头部添加标签内容
在series中添加label标签即可,可以在此标签内进行文本内容的颜色,位置,内容等的设置,如下示例:

series: [
{
name: “直接访问”,
type: “bar”,
barWidth: “40%”,
label: {
show: true,
position: “right”,
color: “#3D383A”,
formatter: “¥{c}”
},
data: [28540, 33534, 9390, 80330, 37220]
}
]

自定义图例修改
如上图所示,我想要自定义设置图例中的文本内容,让图例文本可以换行显示,并且大小颜色可以任意设置,这该如何设置呢?
虽然样式显示并不复杂,但是想在echarts中实现,却是有些麻烦,formatter支持函数自定义修改,我们可以通过此方法来进行设置,将想要显示的内容数据设置成全局变量,然后在此方法中进行操作修改,所有的设置均在legend参数中进行配置。
默认的图例是个方形,如果想要改成圆形,可以将icon设置成circle,即可将图例设置成原型,大小可以通过itemWidth和itemHeight来设置。
示例如下:

legend: {
icon: “circle”, // 将图例设置成原型
bottom: 0,
left: “center”,
itemWidth: 10,
itemHeight: 10,
// itemGap: 10,
formatter: name => {
let data = pieData; // 全局变量
let value = “”;
let price = “”;
for (let i = 0; i < data.length; i++) {
if (data[i].name == name) {
value = data[i].value;
price = data[i].price;
}
}
let arr = [
“{a|” + name + ” ” + value + “%}”,
“{b|¥” + price + “}”
];
return arr.join(“\n”);
},
textStyle: {
rich: {
a: {
fontSize: 12,
width: 100,
align: “left”
},
b: {
width: 100,
fontSize: 14,
align: “left”,
lineHeight: 20,
padding: [0, 0, 5, 0]
}
}
},
data: [“一季度”, “二季度”, “三季度”, “四季度”]
},
var pieData = [
{ value: 28, name: “一季度”, price: 108626.0 },
{ value: 24, name: “二季度”, price: 93108.0 },
{ value: 19, name: “三季度”, price: 73710.0 },
{ value: 29, name: “四季度”, price: 112506.0 }
];

环比图中间显示内容
官方示例中并没有给出环比图中间显示自定义图文的内示例,有个示例是,点击圆环内容,中间显示点击区域对应的内容名称,这个太过简单,并不能满足自定义中间区域图文的要求,想要实现这种要求,就需要用到graphic,在使用时需要单独引用出来,否则会报错,这是一个原生图形元素组件支持image,text,circle等元素。
使用示例如下:

options: {

graphic: {
type: “group”,
top: “middle”,
left: “center”,
height: 80,
children: [
{
type: “text”,
left: “center”,
top: “30%”,
style: {
text: “全年总业绩”,
textAlign: “center”,
textVerticaAlign: “middle”,
fill: “#999”,
font: “15px ‘Helvetica’,sans-serif”
}
},
{
type: “text”,
top: “60%”,
left: “center”,
position: [0, 10],
style: {
text: “9912322.00”,
textAlign: “center”,
textVerticaAlign: “middle”,
fill: “#3d383a”,
font: “22px ‘Helvetica’,sans-serif”
}
}
]
},

}
““

AVUE

axios发送post请求,将数据以表单形式提交

axios 请求配置中,transformRequest配置允许在向服务器发送前,修改请求数据。
// transformRequest 允许在向服务器发送前,修改请求数据
// 只能用在 ‘PUT’, ‘POST’ 和 ‘PATCH’ 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream

  transformRequest: [function (data) {
    // 对 data 进行任意转换处理
    return data;
  }],

处理方法一:

axios({
  url: '/user',
  method: 'post',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
  transformRequest: [function (data) {
    // Do whatever you want to transform the data
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  }],
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
或可以在main.js中进行配置
// main.js
import Axios from 'axios'
import VueAxios from 'vue-axios'
const MyAxios = Axios.create({
  transformRequest: [function (data) {
    // 将数据转换为表单数据
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
  }],
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
Vue.use(VueAxios, MyAxios)

处理方法二:使用qs模块

先安装qs模块 npm install --save qs
axios({
  url: '/user',
  method: 'post',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
  transformRequest: [function (data) {
    data = Qs.stringify(data);
    return data;
  }],
  headers:{'Content-Type':'application/x-www-form-urlencoded'}
})
})

Spring Cloud Gateway

依赖
<!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
配制
spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: false # true 之前的http://localhost:8081/service-consumer/user/info这样的请求地址也能正常访问,因为这时为每个服务创建了2个router。
          lower-case-service-id: true #转换服务id为小写
      routes:
        - id: service_nacos
          uri: lb://nacos #(注册中心中服务的名称)即service-consumer服务的负载均衡地址,并用StripPrefix的filter 在转发之前将/consumer去掉。
          predicates:
            - Path= /nacos/** #将以/consumer/**开头的请求都会转发到uri为lb://service-consumer的地址上
          filters:
            - StripPrefix=1

Gateway 过滤器

Spring Cloud Gateway的filter生命周期不像Zuul那么丰富,它只有两个:“pre”和“post”:

pre:这种过滤器在请求被路由之前调用。可以利用这个过滤器实现身份验证、在集群中选择请求的微服务、记录调试的信息。

post:这种过滤器在路由到服务器之后执行。这种过滤器可用来为响应添加HTTP Header、统计信息和指标、响应从微服务发送给客户端等。

Spring Cloud gateway的filter分为两种:GatewayFilter和Globalfilter。GlobalFilter会应用到所有的路由上,而Gatewayfilter将应用到单个路由或者一个分组的路由上。

利用Gatewayfilter可以修改请求的http的请求或者是响应,或者根据请求或者响应做一些特殊的限制。更多时候可以利用Gatewayfilter做一些具体的路由配置。

Gateway请求匹配

Gateway网关可以根据不同的方式进行匹配进而把请求分发到不同的后端服务上。

Gateway熔断

Spring Cloud Gateway也可以利用Hystrix的熔断特性,在流量过大时进行服务降级,同时项目中必须加上Hystrix的依赖。

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

Gateway重试路由器

Retry GatewayFilter通过四个参数来控制重试机制,参数说明如下:

retries:重试次数,默认值是 3 次。

statuses:HTTP 的状态返回码,取值请参考:org.springframework.http.HttpStatus。

methods:指定哪些方法的请求需要进行重试逻辑,默认值是 GET 方法,取值参考:org.springframework.http.HttpMethod。

series:一些列的状态码配置,取值参考:org.springframework.http.HttpStatus.Series。符合的某段状态码才会进行重试逻辑,默认值是 SERVER_ERROR,值是 5,也就是 5XX(5 开头的状态码),共有5个值。

使用上述配置进行测试,当后台服务不可用时,会在控制台看到请求三次的日志,证明此配置有效。

Gateway 限流操作

Spring Cloud Gateway本身集成了限流操作,Gateway限流需要使用Redis,pom文件中添加Redis依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
    </dependency>
配置了Redis的信息,并配置了RequestRateLimiter的限流过滤器,该过滤器需要配置三个参数:
    BurstCapacity:令牌桶的总容量。
    replenishRate:令牌通每秒填充平均速率。
    Key-resolver:用于限流的解析器的Bean对象的名字。它使用SpEL表达式#{@beanName}从Spring容器中获取bean对象。
    注意:filter下的name必须是RequestRateLimiter。
Key-resolver参数后面的bean需要自己实现,然后注入到Spring容器中。KeyResolver需要实现resolve方法,比如根据ip进行限流,则需要用hostAddress去判断。

自定义Gatewayfilter

Spring Cloud Gateway自定义过滤器,过滤器需要实现GatewayFilter和Ordered这两个接口。
再将该过滤器注册到router中

    private static final Log log = LogFactory.getLog(GatewayFilter.class);
    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if (startTime != null) {
                        log.info("请求路径:"+exchange.getRequest().getURI().getRawPath() + "消耗时间: " + (System.currentTimeMillis() - startTime) + "ms");
                    }
                })
        );
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
注册
    @Bean
        public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
            return builder.routes()
                    .route(r -> r.path("/user/**")
                            .filters(f -> f.filter(new RequestTimeFilter())
                                    .addResponseHeader("X-Response-Default-Foo", "Default-Bar"))
                            .uri("http://localhost:8504/user/info")
                            .order(0)
                            .id("customer_filter_router")
                    )
                    .build();
        }
除了上述代码的方式配置我们自定义的过滤器的方式之外,也可以在application.yml文件中直接配置

自定义GlobalFilter

Spring Cloud Gateway根据作用范围分为GatewayFilter和GlobalFilter,二者区别如下:

GatewayFilter : 需要通过spring.cloud.routes.filters 配置在具体路由下,只作用在当前路由上或通过spring.cloud.default-filters配置在全局,作用在所有路由上。
GlobalFilter:全局过滤器,不需要在配置文件中配置,作用在所有的路由上,最终通过GatewayFilterAdapter包装成GatewayFilterChain可识别的过滤器,它为请求业务以及路由的URI转换为真实业务服务的请求地址的核心过滤器,不需要配置,系统初始化时加载,并作用在每个路由上。
public class TokenFilter implements GlobalFilter, Ordered {
    Logger logger= LoggerFactory.getLogger( TokenFilter.class );
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (token == null || token.isEmpty()) {
            logger.info( "token 为空,无法进行访问." );
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

rancher 负载均衡时 default backend – 404

Nacos

官方网址:http://nacos.io
官网教程

docker

https://github.com/nacos-group/nacos-docker.git
https://hub.docker.com/r/nacos/nacos-server/tags?page=1&ordering=last_updated
docker pull nacos/nacos-server:2.0.0
docker pull nacos/nacos-server:latest

单机内存
docker run --name nacos-standalone -e MODE=standalone -p 8848:8848 -d --restart=always nacos/nacos-server:2.0.0
单机Mysql
docker run -d \
--name nacos-server \
-e PREFER_HOST_MODE=hostname \
-e MODE=standalone \
-e SPRING_DATASOURCE_PLATFORM=mysql \
-e MYSQL_MASTER_SERVICE_HOST=172.16.0.17 \
-e MYSQL_MASTER_SERVICE_PORT=3306 \
-e MYSQL_MASTER_SERVICE_USER=root \
-e MYSQL_MASTER_SERVICE_PASSWORD=root \
-e MYSQL_MASTER_SERVICE_DB_NAME=nacos \
-e MYSQL_SLAVE_SERVICE_HOST=192.168.1.3 \
-e MYSQL_SLAVE_SERVICE_PORT=3306 \
-p 8848:8848 \
--restart=always \
nacos/nacos-server:2.0.0

mkdir logs
mkdir properties
vi custom.properties

server.contextPath=/nacos
server.servlet.contextPath=/nacos
server.port=8848

spring.datasource.platform=mysql

db.num=1
db.url.0=jdbc:mysql://172.16.0.17:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=PW

nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false

management.metrics.export.elastic.enabled=false
management.metrics.export.influx.enabled=false

server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i

nacos.security.ignore.urls=/,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/login,/v1/console/health/**,/v1/cs/**,/v1/ns/**,/v1/cmdb/**,/actuator/**,/v1/console/server/**
nacos.naming.distro.taskDispatchThreadCount=1
nacos.naming.distro.taskDispatchPeriod=200
nacos.naming.distro.batchSyncKeyCount=1000
nacos.naming.distro.initDataRatio=0.9
nacos.naming.distro.syncRetryDelay=5000
nacos.naming.data.warmup=true
nacos.naming.expireInstance=true

docker  run \
--name nacos -d \
-p 8848:8848 \
--privileged=true \
--restart=always \
-e JVM_XMS=256m \
-e JVM_XMX=256m \
-e MODE=standalone \
-e PREFER_HOST_MODE=hostname \
-v ~/nacos/logs:/home/nacos/logs \
-v ~/nacos/custom.properties:/home/nacos/init.d/custom.properties \
nacos/nacos-server:2.0.0

2.下载源码或者安装包

你可以通过源码和发行包两种方式来获取 Nacos。
从 Github 上下载源码方式
git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U
ls -al distribution/target/
// change the $version to your actual path
cd distribution/target/nacos-server-$version/nacos/bin
下载编译后压缩包方式
您可以从 最新稳定版本 下载 nacos-server-$version.zip 包。
unzip nacos-server-$version.zip 或者 tar -xvf nacos-server-$version.tar.gz
cd nacos/bin
3.启动服务器
Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式):
sh startup.sh -m standalone
如果您使用的是ubuntu系统,或者运行脚本报错提示[[符号找不到,可尝试如下运行:

bash startup.sh -m standalone
Windows
启动命令:
cmd startup.cmd
或者双击startup.cmd运行文件。
4.服务注册&发现和配置管理
服务注册
curl -X POST ‘http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=nacos.naming.serviceName&ip=20.18.7.10&port=8080’
服务发现
curl -X GET ‘http://127.0.0.1:8848/nacos/v1/ns/instance/list?serviceName=nacos.naming.serviceName’
发布配置
curl -X POST “http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test&content=HelloWorld”
获取配置
curl -X GET “http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test”
5.关闭服务器
Linux/Unix/Mac
sh shutdown.sh
Windows
cmd shutdown.cmd
或者双击shutdown.cmd运行文件。

DOCKER uick Start

Run the following command:

Clone project

git clone --depth 1 https://github.com/nacos-group/nacos-docker.git
cd nacos-docker

Standalone Derby

docker-compose -f example/standalone-derby.yaml up

Standalone Mysql

docker-compose -f example/standalone-mysql.yaml up

Cluster

docker-compose -f example/cluster-hostname.yaml up 

Service registration

curl -X PUT 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=nacos.naming.serviceName&ip=20.18.7.10&port=8080'

Service discovery

  curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/instances?serviceName=nacos.naming.serviceName'

Publish config

curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test&content=helloWorld"

Get config

  curl -X GET "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test"

Open the Nacos console in your browser

link:http://127.0.0.1:8848/nacos/ 默认账号密码都是nacos

Common property configuration

name description option
MODE cluster/standalone cluster/standalone default cluster
NACOS_SERVERS nacos cluster address eg. ip1:port1 ip2:port2 ip3:port3
PREFER_HOST_MODE Whether hostname are supported hostname/ip default ip
NACOS_SERVER_PORT nacos server port default 8848
NACOS_SERVER_IP custom nacos server ip when network was mutil-network
SPRING_DATASOURCE_PLATFORM standalone support mysql mysql / empty default empty
MYSQL_SERVICE_HOST mysql host
MYSQL_SERVICE_PORT mysql database port default : 3306
MYSQL_SERVICE_DB_NAME mysql database name
MYSQL_SERVICE_USER username of database
MYSQL_SERVICE_PASSWORD password of database
MYSQL_MASTER_SERVICE_HOST The latest version of the image removes this attribute, using MYSQL_SERVICE_HOST
MYSQL_MASTER_SERVICE_PORT The latest version of the image removes this attribute, using MYSQL_SERVICE_PORT default : 3306
MYSQL_MASTER_SERVICE_DB_NAME The latest version of the image removes this attribute, using MYSQL_SERVICE_DB_NAME
MYSQL_MASTER_SERVICE_USER The latest version of the image removes this attribute, using MYSQL_SERVICE_USER
MYSQL_MASTER_SERVICE_PASSWORD The latest version of the image removes this attribute, using MYSQL_SERVICE_PASSWORD
MYSQL_SLAVE_SERVICE_HOST The latest version of the image removes this attribute
MYSQL_SLAVE_SERVICE_PORT The latest version of the image removes this attribute default :3306
MYSQL_DATABASE_NUM It indicates the number of database default :1
JVM_XMS -Xms default :2g
JVM_XMX -Xmx default :2g
JVM_XMN -Xmn default :1g
JVM_MS -XX:MetaspaceSize default :128m
JVM_MMS -XX:MaxMetaspaceSize default :320m
NACOS_DEBUG enable remote debug y/n default :n
TOMCAT_ACCESSLOG_ENABLED server.tomcat.accesslog.enabled default :false
NACOS_AUTH_SYSTEM_TYPE The auth system to use, currently only ‘nacos’ is supported default :nacos
NACOS_AUTH_ENABLE If turn on auth system default :false
NACOS_AUTH_TOKEN_EXPIRE_SECONDS The token expiration in seconds default :18000
NACOS_AUTH_TOKEN The default token default :SecretKey012345678901234567890123456789012345678901234567890123456789
NACOS_AUTH_CACHE_ENABLE Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay. default : false

集成

<!--阿里依赖管理-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!--nacos-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <!--<version>${latest.version}</version>-->
        </dependency>

spring.application.name=nacos
spring.cloud.nacos.discovery.server-addr=102.168.88.127:8848

在 Nacos Spring Cloud 中,dataId 的完整格式如下:
${prefix}-${spring.profile.active}.${file-extension}

    prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。
    spring.profile.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档。 注意:当 spring.profile.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension}
    file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型。
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.88.127:8848
      config:
        server-addr: 192.168.88.127:8848
        #namespace: example.properties # Data Id
        file-extension: yml # yml or properties

spring注解驱动

容器 AnnotationConfigApplicationContext
组件添加
组件赋值
组件注入
AOP
声明事务

原理
BeanFactoryPostProcessor
BeanDefinitionRegistryPostProcessor
ApplicationListener
Spring容器创建过程

WEB
servlet3.o
异步请求

/**
 * 给容器注册组件
 * 1.包扫描+组件标注注解(@Controller...) [我们自己写的]
 * 2.@Bean+ @Configuration [别人写的,导入的第三方包]
 * 3.@Import [快速的给容器中导入组件]
 *      1. @Import({要导入的容器的组件...}) id默认为全类名
 *      2. @ImportSelector 返回要导入的全类名数组
 *      3. ImportBeanDefinitionRegistrar 通过registerBeanDefinitions给容器中增加自己的bean
 * 4.使用spring提供的FactoryBean[工厂Bean]
 *      1.默认获取到的是工厂Bean调用getObject创建的对象
 *      2.通过前缀&获取FactoryBean注入的工厂bean本身
 * 5.@Condition按条件进行判断,满足条件的给容器中注册Bean
 *
 * 赋值方式
 * 1.xml中指定
 * 2.使用Bean创建时指定
 * 3.使用@Value赋值
 *  1.基本数值
 *  2.SpEL #{}
 *  3.配制文件,运行环境变量中的值 ${} 可以使用@PropertySource加载外部配制文件保存到运行的变量中,yml文件先在静态资源中引入
 *
 * 自动装配
 *  spring利用依赖注入DI,完成对IOC容器中各个组件的依赖关系赋值
 *  默认加在ioc容器中的组件,容器启动会调用无参构造器创建对象,再进行初始化赋值等操作
 *  1.@Autowired 自动注入 [Spring规范]
 *      AutowiredAnnotationBeanPostProcessor:解析完成自动装配功能
 *      1.默认优先按照类型去容器中找对应的组件:applicationContext.getBean(beanName.Class),找到并赋值
 *      2.如果找到多个相同类型的组件,再将属性的名字作为组件的ID去容器中查找 applicationContext.getBean(beanName),找到并赋值
 *      3.@Qualifier("beanName")明确指定要装配的组件ID,而不傅属性
 *      4.自动装配默认一定要将属性赋值好,没有就会报错,可以使用@Autowired(required = false)没有就不装配
 *      5.@Primary spring进行装配的时候,默认使用首选的Bean,也可以继续使用@Qualifier指定
 *  2.还支持@Resource(JSR250规范)和@Inject(JSR330规范)  [java规范]
 *      1.@Resource 可以和@Autowired一样实现自动装配,默认按照组件名称进行装配,不支持@Primary和@Autowired(required = false)
 *      2.@Inject 使用先导入javax.inject依赖,可以和@Autowired一样实现自动装配,支持@Primary和不支持@Autowired(required = false)
 *  3.@Autowired 可以标在构造器,方法,属性,参数;都是从容器中获取参数组件的值
 *      1.标注在方法,spring容器创建当前对角,就会调用方法,完成赋值,方法使用的参数,自定义类型的值从Ioc容器中获取;@Bean标注的方法创建对象的时候,方法参数的值从容器中获取;默认不写@Autowired效果都是一样的
 *      2.标注在有参构造器时,容器启动调用这有参构造器创建对象,构造器要用的组件,都是从容器中获取;只有一个有参构造器时,可以省略@Autowired,参数位置的组件还是从容器中获取
 *      3.标在参数时,也同2
 *  4.自定义组件想要使用spring容器底层的一些组件(applicationContext,BeanFactory,xxx),自定义组件只需实现xxxAWare接口,有回调的风格,总体参照AWare;
 *   xxxAWare的功能使用xxxAWarePostProcessor后置处理器完成
 *  5.@Profile: spring为我们提供可以根据当前环境,动态激活和切换一系列组件的功能,不指定,在任何环境下都能注册
 *      环境切换:
 *          1使用命令行动态参数-Dspring.profiles.active
 *          2使用代码方式,applicationContext不能使用有参构造器,用无参构造器
 *          //指定主配制类,获得容器
 *         //AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfProfile.class);
 *         AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
 *         //使用无参构造器设置需要激活的环境,一次可以设多个
 *         applicationContext.getEnvironment().setDefaultProfiles("test");
 *         //注册主配制类
 *         applicationContext.register(MainConfigOfProfile.class);
 *         //启动刷新容器
 *         applicationContext.refresh();
 *         log.info("容器创建完成...[{}]",applicationContext);
 *         3.使用配制文件spring.profiles.active=dev
 *      1.加了环境标识的Bean,只有在环境激活的情况下注册到容器中,默认是default环境
 *      2.写在配置类上,只有在只有在环境激活的情况下,整个配置类里面的所有配置才生效
 *      3.没有标注的,在任何环境下都是加载的
 *
 */