springcloud 项目demo搭建(springboot 2.5.0版本为例,springcloud 2020.0.3版本为例)

[根据网上视频教程,自己总结搭建的demo(intellij idea 搭建)]

一、先搭建整个系统模块-cloud-rest(自定义)

1.在idea中,File->New->Project


20803578-50e9e1603035d6d6.png

2.点击 Empty Project -> Next


image.png

3.项目名称,项目位置,点击完成
image.png

4.点击ok 即可


image.png

二、搭建注册中心-eureka

1.File->New-Module


image.png

2.点击next


image.png

3.一直下去,直至finish
image.png

4.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>nk.gk.wyl</groupId>
    <artifactId>eureka-server</artifactId>
    <version>1.0</version>
    <name>eureka-server</name>
    <description>注册中心</description>
    <properties>
        <java.version>1.8</java.version>
        <!--  引入springCloud 版本 -->
        <spring-cloud.version>2020.0.3</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 引入eureka 依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
    <!-- 引入cloud 依赖 -->
    <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>
        </dependencies>
    </dependencyManagement>

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

</project>

5.application.yml 文件配置如下

#注册中心的名字
spring:
  application:
    name: eureka-server
server:
  port: 10010

#注册中心相关配置
eureka:
  server:
    # 配置关闭自我保护,并按需配置Eureka Server清理无效节点的时间间隔(5000ms)。
    enable-self-preservation: false
    eviction-interval-timer-in-ms: 5000
  client:
    # 不将自己注册到注册中心
    register-with-eureka: false #fasle:
    # 因为自己是注册中心,因此不用检索服务信息
    fetch-registry: false        #true: Cannot execute request on any know server
    # 注册中心的地址
    service-url:
      defaultZone: http://localhost:10086/eureka/
  instance:
    prefer-ip-address: true
security:
  basic:
    enabled: false

6.在启动类增加@EnableEurekaServer 注解

package nk.gk.wyl.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer // 服务端
@SpringBootApplication
public class EurekaServerApplication {

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

}

7.验证
浏览器访问:http://localhost:10010/

image.png

三、搭建一个简单的系统模块(可自定义,此处定义user)

1.File->New-Module


image.png

2.点击next


image.png

3.一直下去,直至finish
image.png

4.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>nk.gk.wyl</groupId>
    <artifactId>user</artifactId>
    <version>1.0</version>
    <name>user</name>
    <description>用户模块</description>
    <properties>
        <java.version>1.8</java.version>
        <!--  引入springCloud 版本 -->
        <spring-cloud.version>2020.0.3</spring-cloud.version>
    </properties>
    <dependencies>
        <!-- 引入web依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 引入eureka 客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 引入ribbon 依赖 ,用来实现负载均衡,我们这里只是使用先不作其他介绍 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <!-- 引入hystrix 依赖 ,用来实现服务容错保护-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
        <!-- hystrix 引入熔断机制 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.2.9.RELEASE</version>
        </dependency>


        <!-- feign微服务调用 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!-- 引入swagger -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </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>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

5.application.yml 文件配置如下

spring:
  application:
    name: user
  cloud:
    circuitbreaker:
      hystrix:
        enabled: true

#服务端口
server:
  port: 10011
  servlet:
    context-path: /user-rest
# 注册中心地址
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10010/eureka/
  instance:
    prefer-ip-address: true

#是否激活 swagger true or false
swagger:
  enable: true

6.在启动类增加@EnableFeignClients
@EnableEurekaClient
@EnableHystrix 等注解

package nk.gk.wyl.user;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;

//允许服务调用
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
@EnableHystrix
public class UserApplication {

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

}

7.增加swagger相关配置


image.png

1.Swagger2 java

package nk.gk.wyl.user.config.swagger;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * swagger2的配置文件,在项目的启动类的同级文件建立
 */
@Configuration
@EnableSwagger2
//是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {
    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()

                /**
                 * 为控制层包路径
                 */
                .apis(RequestHandlerSelectors.basePackage("nk.gk.wyl.user.controller")).paths(PathSelectors.any())
                .build();
    }

    /**
     * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                /**
                 * 页面标题
                 */
                .title("基于 SpringBoot  使用 Swagger2 构建 BS 服务-RESTful API")

                /**
                 * 创建人信息
                 */
                .contact(new Contact("zhangshuailing", "https://www.jianshu.com/u/6fa8a7602008", ""))
                /**
                 * 版本号
                 */
                .version("1.0")
                /**
                 * 描述
                 */
                .description("API 接口描述")
                .build();
    }
}

2.SwaggerRestController java

package nk.gk.wyl.user.config.swagger;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Description: 定义接口访问在线api文档
 * @Author: zhangshuailing
 * @CreateDate: 2020/10/15 12:45
 * @UpdateUser: zhangshuailing
 * @UpdateDate: 2020/10/15 12:45
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Controller
@RequestMapping("")
public class SwaggerRestController {

    @GetMapping("")
    public String index() {
        return "redirect:/swagger-ui.html";
    }
}

8.增加一个测试的控制类


image.png
package nk.gk.wyl.user.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
 * @ProjectName: boot-rest
 * @Package: nk.gk.wyl.user.config.controller
 * @ClassName: UserController
 * @Author: zsl
 * @Description: ${description}
 * @Date: 2021/6/6 16:46
 * @Version: 1.0
 */
@RestController
@RequestMapping("user")
@Api(value = "user控制层" ,description = "user控制层")
@Slf4j
public class UserController {

    @GetMapping("index")
    @ApiOperation(value = "测试类")
    public String index(){
        return "user";
    }

    @GetMapping("index1")
    @ApiOperation(value = "测试返回数据")
    public String index1(@RequestParam(value = "名称" ,required = true) String name){
        return name;
    }
}

9.验证
浏览器访问:http://localhost:10011/user-rest

image.png

浏览器访问:http://localhost:10010/
image.png

四、搭建一个简单的系统模块(可自定义,此处定义nlp),用来实现Feign远程调用,Hystrix熔断机制
1.File->New-Module


image.png

2.点击next


image.png

3.一直下去,直至finish
image.png

4.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>nk.gk.wyl.nlp</groupId>
    <artifactId>nlp</artifactId>
    <version>1.0</version>
    <name>nlp</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <!--  引入springCloud 版本 -->
        <spring-cloud.version>2020.0.3</spring-cloud.version>
    </properties>
    <dependencies>
        <!-- 引入web依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 引入eureka 客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- feign微服务调用 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- springboot   mybatis  集成分页插件 -->
        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!-- 引入swagger依赖 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </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>
        </dependencies>
    </dependencyManagement>

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

</project>

5.aplication.yml文件


spring:
  application:
    name: nlp

#服务端口
server:
  port: 10012
  servlet:
    context-path: /nlp-rest

# 注册中心地址
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka/
  instance:
    prefer-ip-address: true

#是否激活 swagger true or false
swagger:
  enable: true

# 配置mongodb数据源(多数据源)
mysql:
  primary:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.116.121:3306/study?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
    username: root
    password: 123456



mybatis:
  configuration:
    cache-enabled: false
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

6.启动类增加 @EnableFeignClients
@EnableEurekaClient 依赖

package nk.gk.wyl.nlp.nlp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;


//允许服务调用
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class NlpApplication {

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

}

7.配置主数据库-mysql


image.png
DbConfiguration 文件
package nk.gk.wyl.nlp.config.db.mysql;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @ProjectName: boot-rest
 * @Package: nk.gk.wyl.nlp.config.db.mysql
 * @ClassName: Configuration
 * @Author: zsl
 * @Description: mysql 多数据源数据库配置
 * @Date: 2021/10/22 21:50
 * @Version: 1.0
 */
@Configuration
public class DbConfiguration {


    @Primary
    // 表示这个数据源是默认数据源, 这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)
    @Bean("primaryDataSource")
    @ConfigurationProperties(prefix = "mysql.primary") //读取application.yml中的配置参数映射成为一个对象
    public DataSource getDb1DataSource(@Value("mysql.primary.driverClassName") String driveClass,
                                       @Value("mysql.primary.username") String username,
                                       @Value("mysql.primary.password") String password,
                                       @Value("mysql.primary.url") String url
    ){
        return createDruidDataSource(driveClass,url,username,password);
    }

    /**
     * @param driver 数据库驱动
     * @param url 数据库地址
     * @param username 用户名
     * @param password 密码
     * @return 数据源
     */
    private DataSource createDruidDataSource(String driver, String url, String username, String password) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}
PrimaryConfig 文件
package nk.gk.wyl.nlp.nlp.config.db.mysql;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @ProjectName: boot-rest
 * @Package: nk.gk.wyl.nlp.config.db.mysql
 * @ClassName: PrimaryConfig
 * @Author: zsl
 * @Description: 主数据源配置
 * @Date: 2021/10/22 21:58
 * @Version: 1.0
 */
@Configuration
@MapperScan(basePackages = {"nk.gk.wyl.nlp.mapper.primary"},
        sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryConfig {
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Bean
    public SqlSessionFactory primarySqlSessionFactory(MybatisProperties mybatisProperties) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(primaryDataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:xml/primary/*.xml"));
        factoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(mybatisProperties.getConfiguration());


        return factoryBean.getObject();
    }

    @Bean(name = "primarySqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate() throws Exception {
        MybatisProperties mybatisProperties = new MybatisProperties();
        return new SqlSessionTemplate(primarySqlSessionFactory(mybatisProperties));
    }

}

8.配置swagger

Swagger2文件
package nk.gk.wyl.nlp.nlp.config.swagger;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * swagger2的配置文件,在项目的启动类的同级文件建立
 */
@Configuration
@EnableSwagger2
//是否开启swagger,正式环境一般是需要关闭的(避免不必要的漏洞暴露!),可根据springboot的多环境配置进行设置
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {
    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()

                /**
                 * 为控制层包路径
                 */
                .apis(RequestHandlerSelectors.basePackage("nk.gk.wyl.nlp.controller")).paths(PathSelectors.any())
                .build();
    }

    /**
     * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                /**
                 * 页面标题
                 */
                .title("基于 SpringBoot  使用 Swagger2 构建 BS 服务-RESTful API")

                /**
                 * 创建人信息
                 */
                .contact(new Contact("zhangshuailing", "https://www.jianshu.com/u/6fa8a7602008", ""))
                /**
                 * 版本号
                 */
                .version("1.0")
                /**
                 * 描述
                 */
                .description("API 接口描述")
                .build();
    }
}
SwaggerRestController文件
package nk.gk.wyl.nlp.nlp.config.swagger;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Description: 定义接口访问在线api文档
 * @Author: zhangshuailing
 * @CreateDate: 2020/10/15 12:45
 * @UpdateUser: zhangshuailing
 * @UpdateDate: 2020/10/15 12:45
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Controller
@RequestMapping("")
public class SwaggerRestController {

    @GetMapping("")
    public String index() {
        return "redirect:/swagger-ui.html";
    }
}

五、搭建一个简单的网关系统模块(可自定义,此处定义gateway)
1.File->New-Module


image.png

2.点击next


image.png

3.一直下去,直至finish
image.png

4.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>nk.gk.wyl</groupId>
    <artifactId>gateway</artifactId>
    <version>1.0</version>
    <name>gateway</name>
    <description>网关demo</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2020.0.3</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- feign微服务调用 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </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>
        </dependencies>
    </dependencyManagement>



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

</project>

5.application.yml文件


spring:
  application:
    name: gateway
  cloud:
    gateway:
      enabled: true  #开启网关
      discovery:
        locator:
          enabled: true  #开启自动路由,以服务id建立路由,服务id默认大写
          lower-case-service-id: true  #服务id设置为小写
      #routes:
        #- id: gateway_nlp
          #uri: lb://nlp
          #predicates:
            #- Path=/nlp/**
          #filters:
            #- StripPrefix=1 # 移除前缀 youlai-auth

#服务端口
server:
  port: 10013
  servlet:
    context-path: gateway-rest

# 注册中心地址
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10010/eureka/
  instance:
    prefer-ip-address: true

6.启动类增加@EnableDiscoveryClient注解

package nk.gk.wyl.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {

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

}

7.验证
网关:http://localhost:10013/gateway/user/user-rest/user/name?name=9892

image.png

直接访问接口:http://localhost:10011/user-rest/user/name?name=09901
image.png

网关:http://localhost:10013/gateway/nlp/nlp-rest/api/v1.0/base/findListGet?tableName=test_info
image.png

直接访问接口:http://localhost:10012/nlp-rest/api/v1.0/base/findListGet?tableName=test_info
image.png

六、程序demo地址

链接:https://pan.baidu.com/s/1NedWwvGiy_7t7uf67k7iQQ
提取码:0913

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容