docker-compose安装nacos

news2024/10/5 13:40:14

文章目录

  • 一、安装nacos
    • 1.docker-compose.yml
    • 2.nacos数据库表结构
    • 3.docker-compose 构建运行
    • 4.检查nacos日志
    • 6.测试访问:
    • TODO:
  • 二、nacos为注册中心:项目测试
    • 1.新建maven项目:
    • 2.配置pom.xml
    • 3.配置application.properties
    • 4.激活服务发现客户端
    • 5.编写controller
    • 6.增加远程调用配置
    • 7.启动后查看nacos网页端
    • 8.访问地址
    • 9.测试消费端负载均衡
  • 三.nacos配置中心和注册中心:项目测试
    • 1.新建maven项目
    • 2.配置子项目pom.xml
    • 3.配置bootstrap.properties文件
    • 4.激活服务发现客户端
    • 5.编写controller
    • 6.编写bean,获取远程配置
    • 7.在nacos服务端上增加配置
    • 8.启动config项目
    • 9.访问controller
  • 四、整合gateway网关
    • 1.添加依赖
    • 2.编写配置文件
    • 3.启动项目
    • 4.如何测试网关是否拦截了目标服务器请求


一、安装nacos

安装文档:https://mrbird.cc/Spring-Cloud-Alibaba-Nacos%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83.html

docker-compose安装nacos

创建文件夹:/opt/docker-file/nacos

1.docker-compose.yml

version: "3"
services:
  nacos:
    image: nacos/nacos-server:v2.1.0
    container_name: nacos
    environment:
      # 支持主机名可以使用hostname,否则使用ip,默认ip
      - PREFER_HOST_MODE=ip
      # 单机模式
      - MODE=standalone
      # 数据源平台 支持mysql或不保存empty
      - SPRING_DATASOURCE_PLATFORM=mysql
      # mysql配置,!!!attention必须是mysql所在主机IP
      #- MYSQL_SERVICE_HOST=192.168.0.123
      #- MYSQL_SERVICE_PORT=3306
      #- MYSQL_SERVICE_USER=root
      #- MYSQL_SERVICE_PASSWORD=123456
      #- MYSQL_SERVICE_DB_NAME=nacos
    volumes:
      - ./logs:/home/nacos/logs
      - ./conf:/home/nacos/conf
    ports:
      - 8848:8848 
    restart: always

创建log日志目录及配置文件目录:

mkdir -p /opt/docker-file/nacos/logs
mkdir -p /opt/docker-file/nacos/conf	

将application.properties文件复制到/opt/docker-file/nacos/conf目录下

server.servlet.contextPath=/nacos
server.port=8848
spring.datasource.platform=mysql
# 数据库数量
db.num=1
db.url.0=jdbc:mysql://192.168.229.199:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user=root2
db.password=123456

2.nacos数据库表结构

/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info   */
/******************************************/
CREATE TABLE `config_info` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
  `group_id` VARCHAR(255) DEFAULT NULL,
  `content` LONGTEXT NOT NULL COMMENT 'content',
  `md5` VARCHAR(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` TEXT COMMENT 'source user',
  `src_ip` VARCHAR(50) DEFAULT NULL COMMENT 'source ip',
  `app_name` VARCHAR(128) DEFAULT NULL,
  `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
  `c_desc` VARCHAR(256) DEFAULT NULL,
  `c_use` VARCHAR(64) DEFAULT NULL,
  `effect` VARCHAR(64) DEFAULT NULL,
  `type` VARCHAR(64) DEFAULT NULL,
  `c_schema` TEXT,
  `encrypted_data_key` TEXT NOT NULL COMMENT '秘钥',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_aggr   */
/******************************************/
CREATE TABLE `config_info_aggr` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
  `group_id` VARCHAR(255) NOT NULL COMMENT 'group_id',
  `datum_id` VARCHAR(255) NOT NULL COMMENT 'datum_id',
  `content` LONGTEXT NOT NULL COMMENT '内容',
  `gmt_modified` DATETIME NOT NULL COMMENT '修改时间',
  `app_name` VARCHAR(128) DEFAULT NULL,
  `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_beta   */
/******************************************/
CREATE TABLE `config_info_beta` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
  `group_id` VARCHAR(128) NOT NULL COMMENT 'group_id',
  `app_name` VARCHAR(128) DEFAULT NULL COMMENT 'app_name',
  `content` LONGTEXT NOT NULL COMMENT 'content',
  `beta_ips` VARCHAR(1024) DEFAULT NULL COMMENT 'betaIps',
  `md5` VARCHAR(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` TEXT COMMENT 'source user',
  `src_ip` VARCHAR(50) DEFAULT NULL COMMENT 'source ip',
  `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
  `encrypted_data_key` TEXT NOT NULL COMMENT '秘钥',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_info_tag   */
/******************************************/
CREATE TABLE `config_info_tag` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
  `group_id` VARCHAR(128) NOT NULL COMMENT 'group_id',
  `tenant_id` VARCHAR(128) DEFAULT '' COMMENT 'tenant_id',
  `tag_id` VARCHAR(128) NOT NULL COMMENT 'tag_id',
  `app_name` VARCHAR(128) DEFAULT NULL COMMENT 'app_name',
  `content` LONGTEXT NOT NULL COMMENT 'content',
  `md5` VARCHAR(32) DEFAULT NULL COMMENT 'md5',
  `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  `src_user` TEXT COMMENT 'source user',
  `src_ip` VARCHAR(50) DEFAULT NULL COMMENT 'source ip',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = config_tags_relation   */
/******************************************/
CREATE TABLE `config_tags_relation` (
  `id` BIGINT(20) NOT NULL COMMENT 'id',
  `tag_name` VARCHAR(128) NOT NULL COMMENT 'tag_name',
  `tag_type` VARCHAR(64) DEFAULT NULL COMMENT 'tag_type',
  `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
  `group_id` VARCHAR(128) NOT NULL COMMENT 'group_id',
  `tenant_id` VARCHAR(128) DEFAULT '' COMMENT 'tenant_id',
  `nid` BIGINT(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`nid`),
  UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = group_capacity   */
/******************************************/
CREATE TABLE `group_capacity` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `group_id` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
  `quota` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
  `max_aggr_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';

/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = his_config_info   */
/******************************************/
CREATE TABLE `his_config_info` (
  `id` BIGINT(64) UNSIGNED NOT NULL,
  `nid` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `data_id` VARCHAR(255) NOT NULL,
  `group_id` VARCHAR(128) NOT NULL,
  `app_name` VARCHAR(128) DEFAULT NULL COMMENT 'app_name',
  `content` LONGTEXT NOT NULL,
  `md5` VARCHAR(32) DEFAULT NULL,
  `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `src_user` TEXT,
  `src_ip` VARCHAR(50) DEFAULT NULL,
  `op_type` CHAR(10) DEFAULT NULL,
  `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
  `encrypted_data_key` TEXT NOT NULL COMMENT '秘钥',
  PRIMARY KEY (`nid`),
  KEY `idx_gmt_create` (`gmt_create`),
  KEY `idx_gmt_modified` (`gmt_modified`),
  KEY `idx_did` (`data_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';


/******************************************/
/*   数据库全名 = nacos_config   */
/*   表名称 = tenant_capacity   */
/******************************************/
CREATE TABLE `tenant_capacity` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `tenant_id` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
  `quota` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
  `usage` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '使用量',
  `max_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
  `max_aggr_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
  `max_aggr_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
  `max_history_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
  `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';


CREATE TABLE `tenant_info` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `kp` VARCHAR(128) NOT NULL COMMENT 'kp',
  `tenant_id` VARCHAR(128) DEFAULT '' COMMENT 'tenant_id',
  `tenant_name` VARCHAR(128) DEFAULT '' COMMENT 'tenant_name',
  `tenant_desc` VARCHAR(256) DEFAULT NULL COMMENT 'tenant_desc',
  `create_source` VARCHAR(32) DEFAULT NULL COMMENT 'create_source',
  `gmt_create` BIGINT(20) NOT NULL COMMENT '创建时间',
  `gmt_modified` BIGINT(20) NOT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
  KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';

CREATE TABLE `users` (
	`username` VARCHAR(50) NOT NULL PRIMARY KEY,
	`password` VARCHAR(500) NOT NULL,
	`enabled` BOOLEAN NOT NULL
);

CREATE TABLE `roles` (
	`username` VARCHAR(50) NOT NULL,
	`role` VARCHAR(50) NOT NULL,
	UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
);

CREATE TABLE `permissions` (
    `role` VARCHAR(50) NOT NULL,
    `resource` VARCHAR(255) NOT NULL,
    `action` VARCHAR(8) NOT NULL,
    UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
);

INSERT INTO users (username, PASSWORD, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);

INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');

3.docker-compose 构建运行

[root@localhost nacos]# docker-compose up -d
[+] Running 1/1
 ⠿ Container nacos  Started 

4.检查nacos日志

docker logs -f nacos

需要在conf目录准备log文件:nacos-logback.xml


<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="1 seconds">
    <contextName>logback</contextName>
    <property name="log.path" value="/home/nacos/logs/logback.log" />
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <!-- <filter class="com.example.logback.filter.MyFilter" /> -->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
              <level>ERROR</level>
        </filter>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>
 
    <appender name="file"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern>
        </rollingPolicy>
 
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
    </appender>
 
    <root level="debug">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>
 
    <logger name="com.example.logback" level="warn" />
 
</configuration>

继续查看nacos错误日志

如连接不上数据库,就是数据库账号密码没有配对。

6.测试访问:

地址:192.168.229.199:49155/nacos/#/login
账号:nacos
密码:nacos

TODO:

打包成新的镜像放在本地仓库,下次可以直接用

二、nacos为注册中心:项目测试

nacos与springcloud与springcloudalibaba版本对照
在这里插入图片描述
nacos版本:v2.1.0
springboot版本:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

springcloudalibaba与springcloud版本:

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    <com-alibaba-cloud.version>2.1.0.RELEASE</com-alibaba-cloud.version>
</properties>

1.新建maven项目:

在这里插入图片描述
父:spring-cloud-alibaba-nacos-register
子:consumer,provider

2.配置pom.xml

spring-cloud-alibaba-nacos-register

<?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>cc.mrbird</groupId>
    <artifactId>spring-cloud-alibaba-nacos-register</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>provider</module>
        <module>consumer</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
        <com-alibaba-cloud.version>2.1.0.RELEASE</com-alibaba-cloud.version>
    </properties>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${com-alibaba-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

provider

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cc.mrbird</groupId>
        <artifactId>spring-cloud-alibaba-nacos-register</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>provider</artifactId>
    <name>provider</name>
    <description>服务提供端</description>

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

consumer

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cc.mrbird</groupId>
        <artifactId>spring-cloud-alibaba-nacos-register</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>consumer</artifactId>
    <name>consumer</name>
    <description>服务消费端</description>

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

3.配置application.properties

provider

server.port=8001
spring.application.name=nacos-producer
spring.cloud.nacos.discovery.server-addr=192.168.229.199:8848
management.endpoints.web.exposure.include=*

comsumer

server.port=8002
spring.application.name=nacos-consumer
spring.cloud.nacos.discovery.server-addr=192.168.229.199:8848
management.endpoints.web.exposure.include=*

4.激活服务发现客户端

启动类加注解@EnableDiscoveryClient

5.编写controller

provider

package cc.mrbird.provider.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("provide")
public class HelloController {

    @GetMapping("{message}")
    public String hello(@PathVariable String message) {
        return String.format("hello %s", message);
    }
}

consumer

package cc.mrbird.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consume")
public class ConsumeController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("hello/{message}")
    public String hello(@PathVariable String message) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-producer");
        String path = String.format("http://%s:%s/provide/%s", serviceInstance.getHost(), serviceInstance.getPort(), message);
        String result = restTemplate.getForObject(path, String.class);
        return String.format("%s from %s %s", result, serviceInstance.getHost(), serviceInstance.getPort());
    }

}

6.增加远程调用配置

consumer

package cc.mrbird.consumer.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConsumerConfigure {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

7.启动后查看nacos网页端

http://192.168.229.199:8848/nacos/#/serviceManagement
如图:
在这里插入图片描述

8.访问地址

服务提供者:localhost:8001/provide/nacos
服务消费者:localhost:8002/consume/hello/nacos

9.测试消费端负载均衡

启动两个provider:
localhost:8001/provide/nacos
localhost:8009/provide/nacos

在这里插入图片描述
在这里插入图片描述

三.nacos配置中心和注册中心:项目测试

java项目如果启动了配置中心,在项目不重启的情况下,可以远程动态的修改配置信息

1.新建maven项目

在spring-cloud-alibaba-nacos-register项目下新建子项目config

2.配置子项目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">
    <parent>
        <artifactId>spring-cloud-alibaba-nacos-register</artifactId>
        <groupId>cc.mrbird</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>config</artifactId>
    <description>配置服务</description>

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-nacos-config</artifactId>
        </dependency>
    </dependencies>

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

</project>

3.配置bootstrap.properties文件

必须是bootstrap.properties文件,不然加载不到

server.port=8102
spring.cloud.nacos.config.server-addr=192.168.229.199:8848
#spring.cloud.nacos.config.file-extension=properties
spring.application.name=nacos-config-example

spring.cloud.nacos.discovery.server-addr=192.168.229.199:8848
management.endpoints.web.exposure.include=*

4.激活服务发现客户端

package cc.mrbird.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties
public class ConfigApplication {

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

5.编写controller

package cc.mrbird.config.controller;


import cc.mrbird.config.config.UserConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("config")
public class Controller {

    @Autowired
    private UserConfig userConfig;

    @GetMapping("hello/{message}")
    public String sayHello(@PathVariable String message) {
        return this.userConfig.getUsername() + message + ";" + this.userConfig.getAge();
    }

}

6.编写bean,获取远程配置

package cc.mrbird.config.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "user")
//@Component
@Configuration
@Data
public class UserConfig {

    private String username;

    private int age;
}

7.在nacos服务端上增加配置

注意dataId的命名方式
在这里插入图片描述

8.启动config项目

没有报错,说明配置没有问题

9.访问controller

localhost:8102/config/hello/nacos

修改nacos服务端配置后再次访问:成功

四、整合gateway网关

1.添加依赖

注释web依赖
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-web</artifactId>-->
<!--        </dependency>-->

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2.编写配置文件

spring:
  gateway:
      routes:
        - id: gateway-test  # 访问http://localhost:8801/gateway-test/test/index,会跳转到访问到 http://localhost:8802/gateway-test/test/index地址
          uri: lb://gateway-test
          order: 0
          predicates:
            - Path=/gateway-test/**
          filters:
            - StripPrefix=1
            
management:
  endpoints:
    web:
      exposure:
        include: '*'

3.启动项目

4.如何测试网关是否拦截了目标服务器请求

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/47192.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

117.Django-缓存redis

1. 概述 ​ 动态网站的基本权衡是&#xff0c;它们是动态的。每次用户请求页面时&#xff0c;Web服务器都会进行各种计算 - 从数据库查询到模板呈现再到业务逻辑 - 以创建站点访问者看到的页面。从处理开销的角度来看&#xff0c;这比标准的文件读取文件系统服务器要耗时多了。…

数据库、计算机网络,操作系统刷题笔记4

数据库、计算机网络&#xff0c;操作系统刷题笔记4 2022找工作是学历、能力和运气的超强结合体&#xff0c;遇到寒冬&#xff0c;大厂不招人&#xff0c;可能很多算法学生都得去找开发&#xff0c;测开 测开的话&#xff0c;你就得学数据库&#xff0c;sql&#xff0c;oracle&…

【POJ No. 1195】 矩形区域查询 Mobile phones

【POJ No. 1195】 矩形区域查询 Mobile phones 北大 OJ 题目地址 【题意】 移动电话的基站区域分为多个正方形单元&#xff0c;形成S S 矩阵&#xff0c;行和列的编号为0&#xff5e;S -1&#xff0c;每个单元都包含一个基站。一个单元内活动手机的数量可能发生变化&#xff…

[附源码]Python计算机毕业设计Django大学生考勤管理系统论文

项目运行 环境配置&#xff1a; Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术&#xff1a; django python Vue 等等组成&#xff0c;B/S模式 pychram管理等等。 环境需要 1.运行环境&#xff1a;最好是python3.7.7&#xff0c;…

区块链存储优化——从MPT树到KV存储

MPT树存储的优缺点 区块链如果采用MPT树存储&#xff0c;大概会有以下优点&#xff1a; 可用全局数据的根哈希做共识&#xff0c;数据篡改会被立即发现&#xff1b;可以查询任意历史区块对应时刻的所有数据&#xff1b;方便从指定区块开始同步数据&#xff0c;因为正如上面所…

Codeforces Round #790 (Div. 4) G. White-Black Balanced Subtrees 感觉很好的树形dp的板子题

翻译&#xff1a; 您得到一个有根的树&#xff0c;其中包含从1到&#x1d45b;编号为&#x1d45b;的顶点。根结点是顶点1。还有一个字符串&#x1d460;表示每个顶点的颜色:如果&#x1d460;&#x1d456;&#x1d671;&#xff0c;那么顶点&#x1d456;是黑色的&#xff0…

MongoDB实战:应用场景以及Spring和mongodb的整合

前言 mongodb是非关系型数据库&#xff0c;他的存储数据可以超过上亿条&#xff08;老版本的mongodb有丢数据的情况&#xff0c;新版本不会有&#xff0c;网上说的&#xff09;&#xff0c;mongodb适合存储 一些量大表关系较简单的数据&#xff0c;例如用户信息&#xff0c;用户…

linux 多台机器修改时间同步

修改东八区 首先第一步&#xff0c;通过命令 &#xff1a;date -R 查看当前系统所在时区。如是0800&#xff0c;则是东八区&#xff0c;也就是我们当下的北京时间&#xff0c;如不是&#xff08;如下图&#xff09;&#xff0c;做如下调整。 命令行键入命令&#xff1a;tzsele…

认识与了解前端Dom

Dom 文档对象模型 Dom是关于创建&#xff0c;修改&#xff0c;插入&#xff0c;删除页面元素的标准 Dom赋予我们操作操作页面的能力 页面的内容都是字符串&#xff0c;js会把这些字符串转换成DOM树&#xff0c;DOM树会把字符串转换成节点&#xff0c;其实我们操作DOM的根本就…

CSS布局的三种方式

绝对定位 绝对定位&#xff1a; ​ 属性&#xff1a;position 值&#xff1a;absolute <style> p.abs{position: absolute;left: 150px;top: 50px; }</style><p >正常文字1</p> <p >正常文字2</p> <p class"abs" >绝对定…

Postman常用断言功能解析

一、Postman断言模块 二、七种常规业务断言 前4种最常用&#xff1a; 1&#xff09;Status code:Code is 200 检查返回的状态码是否为200 2&#xff09;Response body:Contains string 检查响应中包括指定字符串 3&#xff09;Response body:Json value check 检查响应中其中js…

C++ Reference: Standard C++ Library reference: Containers: list: list: cbegin

C官网参考链接&#xff1a;https://cplusplus.com/reference/list/list/cbegin/ 公有成员函数 <list> std::list::cbegin const_iterator cbegin() const noexcept; 返回开始的常量迭代器 返回指向容器第一个元素的const_iterator对象。 const_iterator是指向const内容…

不用ps也能在线设计电商详情页的方法

食品类的商品要如何设计排版详情页呢&#xff1f;怎么样排版食品类商品的详情页才好看&#xff1f;想设计一张好看食品的详情页其实是有方法的&#xff0c;下面跟着小编学习如何使用在线工具乔拓云&#xff0c;在线设计一个食品商品的详情页&#xff0c;还有海量的商品详情页模…

mysql索引类别和失效场景

首先&#xff0c;我们为什么要使用索引&#xff0c;索引有什么作用呢&#xff1f; 索引可以用来快速查询数据表中有某一特定值的记录&#xff0c;大大加快数据的查询速度&#xff1b;在列上创建了索引之后&#xff0c;查找数据时可以直接根据该列上的索引找到对应记录行的位置…

经典文献阅读之--PL-SLAM(点线SLAM)

0. 简介 之前作者基本都在围绕着特征点提取的路径在学习&#xff0c;最近看到了最近点云PCL推送的《Structure PLP-SLAM: Efficient Sparse Mapping and Localization using Point, Line and Plane for Monocular, RGB-D and Stereo Cameras》。这个工作是基于OpenVSLAM架构的…

测评 | 基于AM5708开发板——AM5708 SOC使用uboot更新uboot

本次测评板卡是创龙科技旗下的TL570x-EVM,它是一款基于TI Sitara系列AM5708ARM Cortex-A15+浮点DSPC66x处理器设计的异构多核SOC评估板,由核心板和评估底板组成。核心板经过专业的PCB Layout和高低温测试验证,稳定可靠,可满足各种工业应用环境。 评估板接口资源丰富,引出…

学苑教育杂志学苑教育杂志社学苑教育编辑部2022年第32期目录

前沿 学苑简讯《学苑教育》投稿&#xff1a;cn7kantougao163.com 4-6 专题研究 把握有效生成 焕发课堂魅力——小学语文课堂有效动态生成策略探析 任云青; 7-811 教育管理 新课程理念下高中契约式班级管理研究 孙磊; 9-11 小学班级管理中文明礼仪教育实施策略的…

Ubuntu 20.04 上学习Open vSwitch :VxLAN

参考 OpenvSwitch完全使用手册 云计算底层技术-使用openvswitch Open vSwitch 概述&#xff1b;OVS支持的功能&#xff1b;ovs的模块介绍&#xff08;ovs-vswitchd、ovsdb-server等等 学习环境 学习 OpenStack 2 个 Hyper-V 虚拟机 Ubuntu 20.04 203.0.113.101 /24 ( 网关&a…

Git——入门介绍

目录1.Git概述1.1.版本控制1.2.版本控制工具1.2.1集中式版本控制工具1.2.2分布式版本控制工具1.3.Git 工作机制1.4.Git 和代码托管中心2.Git下载安装2.1.Git下载2.2.Git安装3.Git常用命令3.1.设置用户签名3.2.初始化本地库3.3.查看本地库状态3.4.添加暂存区3.5.提交本地库3.6.修…

6、python的高级特性(生成式、生成器、闭包、装饰器)

文章目录生成式列表生成式字典生成式集合生成式生成器生成器的实现方式将生成式改写成生成器。将[ ] 改成 ( )使用yield关键字闭包装饰器生成式 列表生成式 在“先有一个空列表&#xff0c;然后通过循环依次将元素添加到列表中”的场景&#xff0c;可以使用列表生成式。 列表…