从零开始搭建springCloud项目

先下载nacos.要能登录就行。要注意放开相关端口

docker run -d --name nacos --restart=always --network=host -e MODE=standalone        -p 9848:9848 -p 9849:9849 -p 8848:8848   nacos/nacos-server

创建父工程,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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>obwt-cloud</artifactId>
    <groupId>com.obwt</groupId>
    <version>0.0.1-SNAPSHOT</version>
    <!--用来存放子项目 在子项目为创建的时候可以先注释-->
    <modules>
        <module>bms-cloud</module>
        <module>gateway-cloud</module>
        <!--        <module>tms-cloud</module>-->
<!--        <module>wms-cloud</module>-->
<!--        <module>oms-cloud</module>-->
    </modules>
    <packaging>pom</packaging>

    <!--统一对jar包版本进行管理
    子模块继承之后,提供作用: 锁定版本+子modlue不用写groupId和version -->
    <properties>
        <!-- 指定SpringBoot版本 -->
        <spring-boot.version>2.5.3</spring-boot.version>
        <!-- 指定SpringCloud版本 -->
        <spring-cloud.version>2020.0.3</spring-cloud.version>
        <!-- 指定SpringCloudAlibaba版本 -->
        <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
        <alibaba.nacos.version>2.0.3</alibaba.nacos.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.18.14</lombok.version>
        <mysql.version>5.1.41</mysql.version>
        <druid.version>1.2.6</druid.version>
        <mybatis.spring.boot.version>2.2.0</mybatis.spring.boot.version>
        <mybaits.plus.version>3.3.2</mybaits.plus.version>
        <alibaba.json.version>1.2.75</alibaba.json.version>
        <!--指定jdk版本-->
        <java.version>1.8</java.version>
        <spring-cloud-starter-bootstrap.version>3.0.2</spring-cloud-starter-bootstrap.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <!--spring boot 2.2.2-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud Hoxton.SR1-->
            <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>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
                <optional>true</optional>
            </dependency>
            <!-- bootstrap 启动器 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-bootstrap</artifactId>
                <version>${spring-cloud-starter-bootstrap.version}</version>
            </dependency>
            <!--mybatis plus-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybaits.plus.version}</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-core</artifactId>
                <version>${mybaits.plus.version}</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-extension</artifactId>
                <version>${mybaits.plus.version}</version>
                <scope>compile</scope>
            </dependency>
            <!--json-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>${alibaba.json.version}</version>
            </dependency>
        </dependencies>

    </dependencyManagement>


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

</project>

创建子模块,gateway-cloud

<?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>
    <parent>
        <groupId>com.obwt</groupId>
        <artifactId>obwt-cloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>gateway-cloud</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>


        <!--nacos-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>


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

    </dependencies>

</project>
server:
  port: 8888
spring:
  application:
    # 服务名称
    name: gateway-cloud
  profiles:
    active: dev
  cloud:
    nacos:
      #discovery 服务注册
      discovery:
        server-addr:  0:8848
        #分组
        group: DEFAULT_GROUP
        # 注册到nacos上的服务名称,默认{${spring.application.name}
        service: ${spring.application.name}
        namespace: 96ee7 f50 #命
      #config 读取nacos上的服务配置
      config:
        file-extension: yaml
        #分组
        group: DEFAULT_GROUP
        server-addr:  0:8848
        namespace: 96ee7 f50 #命


 

他会去nacos获取相应配置。

spring:
  cloud:
    # Spring Cloud Gateway 配置项,对应 GatewayProperties 类
    gateway:
      # 路由配置项,对应 RouteDefinition 数组
      routes:
        - id: yudaoyuanma # 路由的编号
          uri: http://www.iocoder.cn # 路由到的目标地址
          predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
            - Path=/blog
          filters:
            - StripPrefix=1
        - id: oschina # 路由的编号
          uri: https://www.oschina.net # 路由的目标地址
          predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
            - Path=/oschina
          filters: # 过滤器,对请求进行拦截,实现自定义的功能,对应 FilterDefinition 数组
            - StripPrefix=1

这样就可以动态修改路由了。

可以按照路由访问8888端口,/blog,就跳到其他站点了。

下载代码:https://download.csdn.net/download/ldy889/89320374

另外一套可以参考品达通用权限

开始创建一个自定义的starter,

在pom里添加,官方的springboot,完整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>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath/>
</parent>
    <groupId>org.example</groupId>
    <artifactId>hello-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
    </dependencies>
</project>

package com.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/*
* 配置属性类
*
* */
@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
    private String name;
    private String url;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
    @Override
    public String toString() {
        return "HelloProperties{" +
                "name='" + name + '\'' +
                ", url='" + url + '\'' +
                '}';
    }

}







package com.example.service;

public class HelloService {

    private String name;
    private String url;


    public HelloService(String name, String url ) {
        this.name = name;
        this.url = url;
    }

    public String sayHello( ) {
        return  "Hello " + name + " from " + url;
    }
}





package com.example.config;

import com.example.service.HelloService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloServiceAutoConfiguration {

    private HelloProperties helloProperties;

    public HelloServiceAutoConfiguration(HelloProperties helloProperties)
    {
        this.helloProperties = helloProperties;
    }

    @ConditionalOnMissingBean
    @Bean
    public HelloService helloService()
    {
        return new HelloService(helloProperties.getName(),helloProperties.getUrl());
    }


}

虽然有报错,说需要什么,但先不管。

maven install

接下来创建myapp来使用这个starter

server:
  port: 8080

hello:
  name: "hello"
  url: "http://localhost:8081"

package org.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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


package org.example.controller;

import com.example.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @Autowired
    private HelloService helloService;

    @RequestMapping("/say")
    public String sayHello() {
        return helloService.sayHello();
    }
}

你看前面那个错提示。现在报错了。

我们在这里加上这个注解,提示消失了。再次maven install ,和启动helloApplication .

这样竟然就完成了自动配置的Bean

继续完善自定义的starter,添加两个依赖。添加mvc拦截用来显示接口使用时间。

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
package com.example.log;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface MyLog {

    String desc() default "";
}



package com.example.log;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class MyLogInterceptor extends HandlerInterceptorAdapter {
    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        MyLog annotation = method.getAnnotation(MyLog.class);
        if(annotation != null){
            startTimeThreadLocal.set(System.currentTimeMillis());
        }

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        MyLog annotation = method.getAnnotation(MyLog.class);
        if(annotation != null){
            long startTime = startTimeThreadLocal.get();
            long endTime = System.currentTimeMillis();
            System.out.println("请求uri:" + request.getRequestURI());
            System.out.println("方法名:" + method.getDeclaringClass().getName()
                    + "." + method.getName());
            System.out.println("方法描述:" + annotation.desc());
            System.out.println("方法执行时间:" + (endTime -  startTime) + "ms");
            startTimeThreadLocal.set(System.currentTimeMillis());
        }
        super.postHandle(request, response, handler, modelAndView);
    }
}


package com.example.config;

import com.example.log.MyLogInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer
{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new MyLogInterceptor());
    }
}


org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.config.HelloServiceAutoConfiguration,\
  com.example.config.MyLogAutoConfiguration

重新install 下。在控制器添加注解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东宇科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值