Nacos常规配置快速入门

Nacos

Nacos 简介

简介

Nacos是针对微服务架构中的服务发现、配置管理、服务治理的综合性解决方案。

特性

服务发现与服务健康检查
动态配置管理
动态DNS服务
服务和元数据管理

安装

下载压缩包

https://github.com/alibaba/nacos

在这里插入图片描述

在bin目录里面启动windows命令

startup.cmd -m standalone (本机启动)

http://localhost:8848/nacos/index.html

默认用户名:nacos,默认密码:nacos
Nacos常规配置快速入门_第1张图片
页面即可访问
Nacos常规配置快速入门_第2张图片

1.新建maven项目父工程 nocasconfig pom文件

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>com.huiju.nacos</groupId>
    <artifactId>nacos-config</artifactId>
    <version>1.0-SNAPSHOT</version>



    <dependencies>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-api</artifactId>
            <version>1.3.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!--demo1的jar-->
            <dependency>
                <groupId>com.alibaba.nacos</groupId>
                <artifactId>nacos-client</artifactId>
                <version>1.1.3</version>
            </dependency>
            <!-- 导这个包就需要设置配置类WebSecurityConfig-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.1.3.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2:建立子模块 service1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>com.huiju.nacos</groupId>
    <artifactId>service1</artifactId>
    <version>1.0-SNAPSHOT</version>

<parent>
    <groupId>com.huiju.nacos</groupId>
    <artifactId>nacos-config</artifactId>
    <version>1.0-SNAPSHOT</version>

</parent>

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    

    </dependencies>


</project>

3:新建启动类

package mervyn.nacos.service1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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


}

3:增加接口,去读取配置

package mervyn.nacos.service1.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by chenyapeng on 2020/8/18 11:22
 */
@RestController
public class HelloWorld {

    //通过value注解读取配置信息,但无法动态更新配置的修改
    @Value("${common.name}")
    private String config1;

    //配置文件上下文,实现动态获取配置更新
    @Autowired
    private ConfigurableApplicationContext applicationContext;


    @GetMapping("/configs1")
    public String getConfigs1() {
        //读取配置信息,不会时时刷新
//        return config1;
        return config1;
    }

    @GetMapping("/configs2")
    public String getConfigs() {
        //读取配置信息
//        return config1;
        return applicationContext.getEnvironment().getProperty("common.name");
    }

    @GetMapping("/configs3")
    public String getConfigs2() {
        //展示配置文件的多文件配置,还有优先级
        String property = applicationContext.getEnvironment().getProperty("common.name");
        String property1 = applicationContext.getEnvironment().getProperty("common.age");

        String property2 = applicationContext.getEnvironment().getProperty("common.address");
        String property3 = applicationContext.getEnvironment().getProperty("common.birthday");
        String property4 = applicationContext.getEnvironment().getProperty("common.fullname");
        return property+"+"+property1+"+"+property2+"+"+property3+"+"+property4;
    }
}

http://localhost:56010/configs1
Nacos常规配置快速入门_第3张图片
http://localhost:56010/configs3
Nacos常规配置快速入门_第4张图片
Nacos常规配置快速入门_第5张图片
如图展示一个配置文件的格式,其他参照此例
Nacos常规配置快速入门_第6张图片




## 工程demo-service

bootstrap.yml


```javascript
spring:
  profiles:
    active:
#可以配置- dev  - test  - pro
      - chen
  application:
#服务名
    name: demo-web          
  main:
#允许相同类名的bean重复加载,取最后一次bean加载实体
    allow-bean-definition-overriding: true    
  cloud:
    nacos:
      discovery:
# 需要被发现的服务
        service: ${spring.application.name}    
      config:
        shared-configs:
#nacos 客户端配置的common,yml
          - common.yml
#nacos 客户端配置的 命名空间
        namespace: chen
#nacos客户端ip
        server-addr: 192.168.138.166:8848
#配到nacos页面的文件类型
        file-extension: yml     

eapcloud:
  logback:
#系统日志保存目录
    path: /deploy/logs
# 日志级别
    jpaSqlLevel: trace
#可以显示sql的涉及到的参数
    jpaBinderLevel: trace   

demo-service.yml 需配置到nacos 客户端页面


```javascript
# 中间件相关配置
          server:
 #服务的端口号         
            port: 8881

          spring:
            cloud:
              nacos:
                discovery:
# 需要被注册到nacos的服务名
                  service: ${spring.application.name}

demo-web工程

bootstrap.yml
spring:
  profiles:
    active:
    - chen
  application: 
    name: demo-web
  main:
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      discovery:
        service: ${spring.application.name}
      config:
        shared-configs:
        - common.yml
        namespace: chen
        server-addr: 192.168.138.166:8848
        file-extension: yml

eapcloud:
  logback:
    path: /deploy/logs
    jpaSqlLevel: trace
    jpaBinderLevel: trace
demo-web.yml      需配置到nacos 客户端页面
# 中间件相关配置
server:
  port: 8882

spring:
  cloud:
    nacos:
      discovery:
        service: ${spring.application.name}

两个工程公用的数据源,中间件链接、等一些公共信息

common.yml      需配置到nocas客户端
# 中间件相关配置
server:
  max-http-header-size: 102400
  error:
    include-stacktrace: on-trace-param

eapcloud:
  license:
    projectNo: huiju.srm.ent
 #ribbitMQ的相关配置   
  amqp:
    route-key-suffix: ${eapcloud.version}
    connection-factory:
      host: 192.168.138.166
      username: guest
      password: guest
      virtualhost: /

#监控
management:
  endpoints:
    web:
      exposure:
        include: ["*"]

spring:
  profiles: common
  main:
    allow-bean-definition-overriding: true
  redis:
    host: 192.168.138.166
    port: 6379
    password: redis239a
    database: 15
    timeout: 60s
    lettuce:
      pool:
        max-active: -1
        max-idle: 15
        max-wait: -1s
        min-idle: 5
  datasource:
    username: root
    password: 123456
    jdbc-url: jdbc:mysql://192.168.138.166:3306/srment6
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: ${spring.datasource.jdbc-url}?user=${spring.datasource.username}&password=${spring.datasource.password}&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
    hikari:
      maximum-pool-size: 10
  jpa:
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
    open-in-view: false
    hibernate:
      ddl-auto: none
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
  transaction:
    default-timeout: 300 #默认5分钟超时
  cloud:
    config:
      override-none: true
    nacos:
      discovery:
# nacos 页面配置的命名空间
        namespace: chen   
        server-addr: 192.168.138.166    
        group: DEFAULT_GROUP    # nacos 页面配置的组单元名
        service: ${spring.application.name}${eapcloud.version:}

# 这个很重要,处理Forwarding error异常
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 150000000 #断路器的超时时间,断路器的超时时间需要大于ribbon的超时时间,不然不会触发重试。
# ribbon
ribbon:
  ConnectTimeout: 8800000 #ribbon请求连接的超时时间
  ReadTimeout: 8800000 #请求处理的超时时间
  OkToRetryOnAllOperations: true #对所有操作请求都进行重试
  MaxAutoRetries: 1 #对当前实例的重试次数
  MaxAutoRetriesNextServer: 1 #对下个实例的重试次数

huiju:
  amqp:
    route-key-suffix: ${eapcloud.version}
    exchange-mode: topic #topic, fanout, direct, header
    connectionFactory:
      host: 192.168.138.166
      username: guest
      password: guest
      virtualhost: /

在nocas的页面新建命名空间chen

Nacos常规配置快速入门_第7张图片

配置common.yml demo-service.yml demo-web.yml 文件

Nacos常规配置快速入门_第8张图片本地文件和配置文件nameplace均要一致 即 nocas 建的命名空间

你可能感兴趣的:(java)