cloud环境搭建

本文档介绍了如何在Spring Cloud环境下搭建微服务,包括Eureka服务注册与发现,Eureka客户端配置,Feign消费者实现,以及Zuul网关的设置。详细阐述了每个模块的Pom配置、启动类和应用属性配置,并提供了测试代码以验证服务间的通信。最后,给出了执行步骤,指导读者逐步完成微服务的构建和测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1项目结构描述

eureka-server:服务注册模块

euraka-client:服务的提供者

feign:消费者

zuul网管

 

 

2 eureka-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 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.1.3.RELEASE</version>

                     <relativePath/> <!-- lookup parent from repository -->

          </parent>

          <groupId>com.example</groupId>

          <artifactId>eureka-server</artifactId>

          <version>0.0.1-SNAPSHOT</version>

          <name>eureka-server</name>

        <description>Demo project for Spring Boot</description>

 

          <properties>

                     <java.version>1.8</java.version>

                     <spring-cloud.version>Greenwich.SR1</spring-cloud.version>

          </properties>

 

          <dependencies>

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>

        </dependency>

 

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </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>

 

启动类:

package com.example.eurekaserver;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

 

@SpringBootApplication

@EnableEurekaServer

public class EurekaServerApplication {

 

          public static void main(String[] args) {

                    SpringApplication.run(EurekaServerApplication.class, args);

          }

 

}

 

 

application.properties配置

server.port=8070

eureka.server.enable-self-preservation=false

eureka.server.eviction-interval-timer-in-ms=5000

 

eureka.instance.hostname=localhost

eureka.client.register-with-eureka=false

eureka.client.fetch-registry=false

eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka

 

 

 

 

 

3euraka-client:服务的提供者

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.1.3.RELEASE</version>

                     <relativePath/> <!-- lookup parent from repository -->

          </parent>

          <groupId>com.example</groupId>

          <artifactId>eureka-client</artifactId>

          <version>0.0.1-SNAPSHOT</version>

          <name>eureka-client</name>

        <description>Demo project for Spring Boot</description>

 

          <properties>

                     <java.version>1.8</java.version>

                     <spring-cloud-services.version>2.1.2.RELEASE</spring-cloud-services.version>

                     <spring-cloud.version>Greenwich.SR1</spring-cloud.version>

          </properties>

 

          <dependencies>

    <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-web</artifactId>

    </dependency>

 

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </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>io.pivotal.spring.cloud</groupId>

                                         <artifactId>spring-cloud-services-dependencies</artifactId>

                                         <version>${spring-cloud-services.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>

启动类:

package com.example.eurekaclient;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

 

@SpringBootApplication

@EnableDiscoveryClient

public class EurekaClientApplication {

 

          public static void main(String[] args) {

                    SpringApplication.run(EurekaClientApplication.class, args);

          }

 

}

application.properties配置

spring.application.name=eureka-client

server.port=8080

eureka.client.serviceUrl.defaultZone=http://localhost:8070/eureka/

 

 

测试代码:

package com.example.eurekaclient;

 

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

public class MyController {

 

    @RequestMapping(value = "/info", method = RequestMethod.GET)

    public String info() {

        return "Hello, eureka-client";

    }

}

 

 

4feign消费者

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.1.3.RELEASE</version>

                     <relativePath/> <!-- lookup parent from repository -->

          </parent>

          <groupId>com.example</groupId>

          <artifactId>eureka-server</artifactId>

          <version>0.0.1-SNAPSHOT</version>

          <name>eureka-server</name>

        <description>Demo project for Spring Boot</description>

 

          <properties>

                     <java.version>1.8</java.version>

                     <spring-cloud.version>Greenwich.SR1</spring-cloud.version>

          </properties>

 

          <dependencies>

    <dependency>

        <groupId>org.springframework.cloud</groupId>

        <artifactId>spring-cloud-starter-openfeign</artifactId>

    </dependency>

 

    <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-web</artifactId>

    </dependency>

 

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </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>

启动类:

package com.test.feignhystrix;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import org.springframework.cloud.openfeign.EnableFeignClients;

 

@SpringBootApplication

@EnableFeignClients

@EnableEurekaClient

public class FeignHystrixApplication {

 

          public static void main(String[] args) {

                    SpringApplication.run(FeignHystrixApplication.class, args);

          }

 

}

application.properties配置

spring.application.name=feign-hystrix

server.port=8081

eureka.client.serviceUrl.defaultZone=http://localhost:8070/eureka/

 

ribbon.ReadTimeout=5000

ribbon.ConnectionTimeout=5000

 

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000

 

#feign.hystrix.enabled=true

测试代码:

package com.test.feignhystrix;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

@Configuration

public class ConsumerController {

 

    @Autowired

    InfoClient infoClient;

 

    @RequestMapping(value = "/consumerInfo", method = RequestMethod.GET)

    public String consumerInfo(){

        return infoClient.info();

    }

}

 

 

 

 

package com.test.feignhystrix;

 

import org.springframework.cloud.openfeign.FeignClient;

import org.springframework.web.bind.annotation.RequestMapping;

 

//1.name为被调用的服务应用名称.

//2.InfoFallBack作为熔断实现,当请求euraka-client失败时调用其中的方法.

//3.feign配置.

@FeignClient(name = "eureka-client", fallback = InfoFallBack.class, configuration = MyFeignConfig.class)

public interface InfoClient {

 

  //被请求微服务的地址

  @RequestMapping("/info")

  String info();

}

 

 

package com.test.feignhystrix;

 

import org.springframework.stereotype.Component;

 

@Component

public class InfoFallBack implements InfoClient {

    @Override

    public String info() {

        return "fallback info";

    }

}

 

 

package com.test.feignhystrix;

 

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

 

import feign.Logger;

 

@Configuration

public class MyFeignConfig {

 

    /**

     * feign打印日志等级

     * @return

     */

    @Bean

    Logger.Level feignLoggerLeval(){

        return Logger.Level.FULL;

    }

}

 

 

 

5ZUUL网管

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.1.3.RELEASE</version>

                     <relativePath/> <!-- lookup parent from repository -->

          </parent>

          <groupId>com.example</groupId>

          <artifactId>zuul</artifactId>

          <version>0.0.1-SNAPSHOT</version>

          <name>zuul</name>

        <description>Demo project for Spring Boot</description>

 

          <properties>

                     <java.version>1.8</java.version>

                     <spring-cloud-services.version>2.1.2.RELEASE</spring-cloud-services.version>

                     <spring-cloud.version>Greenwich.SR1</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-netflix-zuul</artifactId>

    </dependency>

 

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </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>io.pivotal.spring.cloud</groupId>

                                         <artifactId>spring-cloud-services-dependencies</artifactId>

                                         <version>${spring-cloud-services.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>

启动类:

package com.example.zuul;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

 

@SpringBootApplication

@EnableZuulProxy

@EnableEurekaClient

public class ZuulApplication {

 

          public static void main(String[] args) {

                     SpringApplication.run(ZuulApplication.class, args);

          }

 

}

application.properties配置

spring.application.name=zuul

server.port=8071

eureka.client.serviceUrl.defaultZone=http://localhost:8070/eureka/

 

#zuul.host.connect-timeout-millis=5000

#zuul.host.socket-timeout-millis=5000

 

ribbon.ReadTimeout=5000

ribbon.ConnectionTimeout=5000

 

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000

 

zuul.routes.eureka-client=/api/**

测试代码:

package com.example.zuul;

 

import javax.servlet.http.HttpServletRequest;

 

import org.springframework.stereotype.Component;

import org.springframework.util.StringUtils;

 

import com.netflix.zuul.ZuulFilter;

import com.netflix.zuul.context.RequestContext;

import com.netflix.zuul.exception.ZuulException;

 

@Component

public class AccessFilter extends ZuulFilter {

 

    /**

     * 返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型:

     *  pre:可以在请求被路由之前调用

     *  route:在路由请求时候被调用

     *  post:在route和error过滤器之后被调用

     *  error:处理请求时发生错误时被调用

     * @return

     */

    @Override

    public String filterType() {

        return "pre"; //前置过滤器

    }

 

    @Override

    public int filterOrder() {

        return 0; //过滤器的执行顺序,数字越大优先级越低

    }

 

    @Override

    public boolean shouldFilter() {

        return true;//是否执行该过滤器,此处为true,说明需要过滤

    }

 

    /**

     * 过滤器具体逻辑

     * @return

     * @throws ZuulException

     */

    @Override

    public Object run() throws ZuulException {

        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest request = ctx.getRequest();

        System.out.println(String.format("%s demoFilter request to %s", request.getMethod(), request.getRequestURL().toString()));

        String username = request.getParameter("username");// 获取请求的参数

        if(!StringUtils.isEmpty(username)&&username.equals("bright")){//当请求参数username为“bright”时通过

            ctx.setSendZuulResponse(true);// 对该请求进行路由

            ctx.setResponseStatusCode(200);

            ctx.set("isSuccess", true);// 设值,让下一个Filter看到上一个Filter的状态

            return null;

        }else{

            ctx.setSendZuulResponse(false);// 过滤该请求,不对其进行路由

            ctx.setResponseStatusCode(401);// 返回错误码

            ctx.setResponseBody("{\"result\":\"please login!\"}");// 返回错误内容

            ctx.set("isSuccess", false);

            return null;

        }

    }

}

 

 

 

执行步骤:

1启动eureka-server然后访问http://localhost:8070/查看注册中心是否执行成功

2启动eureka-server然后访问http://localhost:8070/查看” Instances currently registered with Eureka”的列表

3访问http://127.0.0.1:8080/info会返回” Hello, eureka-client”

4启用feign访问http://127.0.0.1:8081/consumerInfo会返回Hello, eureka-client,这次为远程调用

5启动zuul分别访问

http://127.0.0.1:8071/api/info 返回 please login!

http://127.0.0.1:8071/api/info?username=bright返回Hello, eureka-client

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值