SpringCloud使用

一、微服务发现组件Eureka的使用

1.父工程中管理springcloud版本

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.M9</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2.搭建Eureka注册中心

1)创建Eureka注册中心模块tenpower-eureka,添加依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

2)该模块application.yml配置

server:
  port: 6868
eureka:
  client:
    register-with-eureka: false  #是否注册到eureka服务
    fetch-registry: false     #是否从eureka中获取注册信息
    service-url:
      defaultZone: http://127.0.0.1:${server.port}/eureka/

3)编写启动类,注意加上注解@EnableEurekaServer

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

4)运行启动类,浏览器输入 http://localhost:6868/ 测试

3.注册微服务到Eureka注册中心

1)微服务模块添加依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

2)微服务模块application.yml配置

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:6868/eureka/
  instance:
    prefer-ip-address: true #使该微服务在上线后能被跨域访问

3)修改每个服务类的启动类,添加注解@EnableEurekaClient将其注册

@EnableEurekaClient

4)将每个微服务启动起来,会发现eureka的注册列表中可以看到这些微服务了

二、微服务调用组件Feign的使用。注意被调用模块不需任何改动,以下都是在调用模块下的改动

1.在调用模块添加feign依赖

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

2.在启动类额外加注解

@EnableDiscoveryClient
@EnableFeignClients

3.创建client包,包下创建接口

@FeignClient("tenpower-base")   //要调用的服务名
public interface LabelClient {
    @GetMapping("/label/{LabelId}")
    public Result findByLabelId(@PathVariable("LabelId") String id);
}

注意 因为这是接口,所以@PathVariable注解一定要指定参数名称,否则出错

4.修改ProblemController

    @Autowired
    private LabelClient labelClient;

    @GetMapping("/label/{labelId}")
    public Result findLabelById(@PathVariable String labelId) {
        return labelClient.findByLabelId(labelId);
    }

5.测试:http://localhost:9003/problem/label/1 能看到标签的信息

Feign自带负载均衡:当调用多个同名微服务时,多次访问调用者会将访问量均匀分配

猜你喜欢

转载自www.cnblogs.com/naixin007/p/10705339.html