搭建一個簡單的spring cloud項目架子

這是我之前學習spring cloud時搭建的第一個spring cloud項目,從依賴管理到入口類的全部核心(不核心)的代碼,幫助不瞭解spring cloud的你搭建你的第一個spring cloud項目,就算只是來copy依賴也是可以的呀!

一、eureka 服務註冊中心

  • 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>com.sinosoft.bocins.newinterf</groupId>
            <artifactId>hello-spring-cloud-dependencies</artifactId>
            <version>1.0.0.RELEASE</version>
        </parent>
        <artifactId>hello-spring-cloud-eureka</artifactId>
        <version>1.0.0.RELEASE</version>
        <packaging>jar</packaging>
    
        <name>hello-spring-cloud-eureka</name>
        <description>註冊中心</description>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    
  • application.yml配置

    spring:
      application:
        name: eureka-server
    server:
      port: 9000
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8000/eureka/
    
    
  • 入口類

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

二、服務提供者

  • 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>com.sinosoft.bocins.newinterf</groupId>        <artifactId>hello-spring-cloud-dependencies</artifactId>        <version>1.0.0.RELEASE</version>    </parent>    <artifactId>hello-spring-cloud-service-admin</artifactId>    <version>1.0.0.RELEASE</version>    <packaging>jar</packaging>    <name>hello-spring-cloud-service-admin</name>    <description>服務中心</description>    <properties>        <java.version>1.8</java.version>        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>    </properties>    <dependencies>        <!--數據庫-->        <dependency>        <groupId>com.oracle.jdbc</groupId>        <artifactId>ojdbc8</artifactId>        <version>12.2.0.1</version>    </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.cloud</groupId>            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>        </dependency>        <!--入參返參包-->        <dependency>            <groupId>com.sinosoft.bocins.newinterf</groupId>            <artifactId>hello-spring-cloud-model</artifactId>            <version>1.0.0.RELEASE</version>        </dependency>        <dependency>            <groupId>com.sinosoft.bocins.newinterf</groupId>            <artifactId>hello-spring-cloud-entity</artifactId>            <version>1.0.0.RELEASE</version>            <scope>compile</scope>        </dependency>        <!--註冊在監控中-->        <dependency>            <groupId>org.jolokia</groupId>            <artifactId>jolokia-core</artifactId>        </dependency>        <dependency>            <groupId>de.codecentric</groupId>            <artifactId>spring-boot-admin-starter-client</artifactId>            <version>2.0.0</version>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>
    
  • application.yml文件

    spring:
      application:
        name: hello-spring-cloud-service-admin
      datasource:
        driver-class-name: oracle.jdbc.driver.OracleDriver
        url: jdbc:oracle:thin:@21.8.129.162:1521/ncsit
        username: ywusersit
        password: abc
    
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8000/eureka/,http://localhost:9000/eureka/
      instance:
        prefer-ip-address: true
        instance-id: ${spring.cloud.client.ip-address}:${server.port}
        lease-renewal-interval-in-seconds: 5              #發送心跳的間隔
        lease-expiration-duration-in-seconds: 10          #續約到期的時間
    server:
      port: 10006      
    
  • 入口類

    @SpringBootApplication
    @EnableEurekaClient
    @EntityScan("com.sinosoft.hello.spring.cloud.entity")
    public class ServiceAdminApplication {
        public static void main(String[] args) {
            SpringApplication.run(ServiceAdminApplication.class,args);
        }
    }
    
    

三、服務消費者feign 一個服務消費者對應一個服務提供者

feign是ribbon的進化版,在feign中,使用 熔斷類 處理在服務者發生異常,調不同時的異常處理信息。

  • 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>com.sinosoft.bocins.newinterf</groupId>
            <artifactId>hello-spring-cloud-dependencies</artifactId>
            <version>1.0.0.RELEASE</version>
        </parent>
        <artifactId>hello-spring-cloud-web-admin-feign</artifactId>
        <version>1.0.0.RELEASE</version>
        <packaging>jar</packaging>
    
        <name>hello-spring-cloud-web-admin-feign</name>
        <description>中銀新接口微服務平臺系統-Feign客戶端</description>
    
        <dependencies>
            <!--熔斷器儀表盤監控-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <dependency>
                <groupId>com.sinosoft.bocins.newinterf</groupId>
                <artifactId>bocins-newinterf-tool-model</artifactId>
                <version>1.0.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
            <dependency>
                <groupId>com.sinosoft.bocins.newinterf</groupId>
                <artifactId>bocins-newinterf-tool-webserviceclient</artifactId>
                <version>1.0.0.RELEASE</version>
            </dependency>
            <!--註冊在監控中-->
            <dependency>
                <groupId>org.jolokia</groupId>
                <artifactId>jolokia-core</artifactId>
            </dependency>
            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-starter-client</artifactId>
                <version>2.0.0</version>
            </dependency>
            <!--入參返參包-->
            <dependency>
                <groupId>com.sinosoft.bocins.newinterf</groupId>
                <artifactId>hello-spring-cloud-model</artifactId>
                <version>1.0.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>com.sinosoft.bocins.newinterf</groupId>
                <artifactId>hello-spring-cloud-entity</artifactId>
                <version>1.0.0.RELEASE</version>
                <scope>compile</scope>
            </dependency>
        </dependencies>
    </project>
    
    
  • application.yml文件

    spring:
      application:
        name: hello-spring-cloud-web-admin-feign
      boot:
          admin:
            client:
              url: http://localhost:8084
    server:
      port: 8766
    
    eureka:
      client:
        serviceUrl:
          defaultZone: http://localhost:8000/eureka/,http://localhost:9000/eureka/
    
    feign:
      hystrix:
        enabled: true
    
  • 入口類

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
@EnableHystrixDashboard
public class FeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class,args);
    }
}
  • 熔斷監控 (此類用以監控熔斷器發生熔斷的情況,可在端口號後加"/hystrix.stream"進行訪問)

@Configuration
public class HystrixDashboardConfiguration {
    @Bean
    public ServletRegistrationBean getServlet(){
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

  • 熔斷接口 fallback= “當調不通服務提供者時,跳轉執行的類,即熔斷類”

@FeignClient(value = "hello-spring-cloud-service-admin",fallback = SwitchServiceHystrix.class)
public interface SwitchService {
    @RequestMapping(value = "/dispose/dispose",method = RequestMethod.POST)
    String dispose(SwitchDTO switchDTO);
}
  • 熔斷類

    @Component
    @Slf4j
    public class SwitchServiceHystrix implements SwitchService{
        @Override
        public String dispose(SwitchDTO switchDTO) {
            log.info("熔斷處理!!!!");
            return String.format("請求失敗,請檢查網絡連接!!!");
        }
    }
    
    

四、API路由網關zuul

  • 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>com.sinosoft.bocins.newinterf</groupId>
        <artifactId>hello-spring-cloud-dependencies</artifactId>
        <version>1.0.0.RELEASE</version>
    </parent>
    <artifactId>hello-spring-cloud-zuul</artifactId>
    <version>1.0.0.RELEASE</version>
    <packaging>jar</packaging>

    <name>hello-spring-cloud-zuul</name>
    <description>Zuul智能路由模塊</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <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-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--註冊在監控中-->
        <dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>

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

            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <configuration>
                            <tasks>
                                <copy todir="../jarrelease">
                                    <fileset dir="${project.build.directory}">
                                        <include name="*.jar" />
                                    </fileset>
                                </copy>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>


</project>

  • application.yml文件

spring:
  application:
    name: hello-spring-cloud-zuul
  boot:
      admin:
        client:
          url: http://localhost:8084
server:
  port: 8769
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka/,http://localhost:9000/eureka/

zuul:
  routes:
#    api-a:
#      path: /api/a/**
#      serviceId: hello-spring-cloud-web-admin-ribbon
    ebscode:
      path: /dispose/dispose
      serviceId: hello-spring-cloud-web-admin-feign
  • 入口類

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

  • provider錯誤處理 當發生調用失敗時,會執行此類

@Component
public class WebAdminFeignFallbackProvider implements FallbackProvider{
    /**
     * 失敗才調用
     * @return
     */
    @Override
    public String getRoute() {
        return "hello-spring-cloud-web-admin-feign";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String,Object> map = new HashMap<>();
                map.put("status",200);
                map.put("message","無法連接,請檢查您的網絡");
                return new ByteArrayInputStream(objectMapper.writeValueAsString(map).getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                //和 getBody 中的內容一致
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }
        };
    }
}

  • 請求過濾 此方法的添加用以防止別人隨意調用接口,在接口地址上加校驗,若不滿足條件則返回非法請求。

@Component
public class LoginFilter extends ZuulFilter{

    @Override
    public String filterType() {
        return "pre";
    }

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

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        if(token==null){
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            try {
                HttpServletResponse response = currentContext.getResponse();
                response.setContentType("text/html;charset=utf-8");
                currentContext.getResponse().getWriter().write("非法請求");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}

以上!歡迎學習交流

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章