程序员微服务架构和实践Java学习笔记

Spring Cloud(3)——服务消费者

2017-03-30  本文已影响822人  会跳舞的机器人

一、简介

Feign是一个声明式的Web Service客户端,它使得编写Web Serivce客户端变得更加简单。我们只需要使用Feign来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的编码器和解码器。Spring Cloud为Feign增加了对Spring MVC注解的支持,还整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现。

二、项目实例

创建maven工程microservice-consumer-user

1、在pom.xml中添加依赖

 <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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.baibei.comsumer</groupId>
    <artifactId>microservice-consumer-user</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>microservice-consumer-user Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</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>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <finalName>microservice-consumer-user</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2、创建UserConsumerApplication.java

package com.baibei.consumer.user;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @author: 会跳舞的机器人
 * @email:2268549298@qq.com
 * @date: 17/2/17 上午11:45
 * @description:用户服务消费者
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class UserConsumerApplication {

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

3、创建application.properties文件

spring.application.name=microservice-consumer-user
server.port=8005

# 注册中心地址
eureka.client.serviceUrl.defaultZone=http://eureka-server-peer1:8761/eureka/,http://eureka-server-peer2:8762/eureka/,http://eureka-server-peer3:8763/eureka/

# Indicates whether this client should fetch eureka registry information from eureka server
# 客户端是否要从eureka server获取注册信息,默认为true
eureka.client.fetchRegistry=true

# Indicates how often(in seconds) to fetch the registry information from the eureka server
# 从eureka server获取注册信息的频率,默认为30秒,缩短配置时间可以缓解服务上线时间过长的问题
eureka.client.registryFetchIntervalSeconds=10


# 自定义负载均衡策略,microservice-provider-user为服务应用名
microservice-provider-user.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

4、创建UserFeignClient

package com.baibei.consumer.user.service;

import com.baibei.common.core.api.ApiResult;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.*;

/**
 * @author: 会跳舞的机器人
 * @date: 2017/3/29 16:54
 * @description: 用户服务调用端
 */
@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {

    /**
     * 根据ID查找用户
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    ApiResult findUserById(@PathVariable("id") Integer id);


}

5、web层的调用

package com.baibei.consumer.user.controller;

import com.baibei.common.core.api.ApiResult;
import com.baibei.consumer.user.service.UserFeignClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 会跳舞的机器人
 * @email:2268549298@qq.com
 * @date: 17/2/17 上午11:51
 * @description:
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private UserFeignClient userFeignClient;


    /**
     * 根据ID查找用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ApiResult getUser(@PathVariable Integer id) {

        return userFeignClient.findUserById(id);
    }
}

通过注入UserFeignClient即可实现像调用本地方法一样去调用远程服务方法

附录:项目目录截图

image
上一篇下一篇

猜你喜欢

热点阅读