1. 程式人生 > >SpingCloud之feign框架調用

SpingCloud之feign框架調用

for type namespace tco war bind 消費 mode 生產者

1.生產者(沒有什麽特殊性)

技術分享圖片

pom.xml

<?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
> <groupId>com.example</groupId> <artifactId>cloud-provider</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>cloud-provider</name> <description>Demo project for Spring Boot</description
> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Finchley.SR2</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--Service Discovery with Zookeeper--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </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> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url:  jdbc:mysql:///testdb?useSSL=true
    username: root
    password: 123
  cloud:
    zookeeper:
      connect-string: 192.168.3.201:2181
  application:
    name: provider
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mapper/*Mapper.xml

logging:
  level:
    com.example.cloudprovider.mapper: debug

實體類

package com.example.cloudprovider.domain;

import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Setter
@Getter
public class UserInfo {
    private Integer userId;
    private String userName;
    private int userAge;
    private Date userBirth;
}

Mapper

package com.example.cloudprovider.mapper;

import com.example.cloudprovider.domain.UserInfo;

public interface UserInfoMapper {
    UserInfo getUser(Integer userId);
}

Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.cloudprovider.mapper.UserInfoMapper">
    <select id="getUser" resultType="com.example.cloudprovider.domain.UserInfo">
        select user_id, user_name, user_age, user_birth from t_user where user_id = #{userId}
    </select>
</mapper>

Service接口

package com.example.cloudprovider.service;

import com.example.cloudprovider.domain.UserInfo;

public interface UserService {
    UserInfo getUser(Integer userId);
}

Service實現

package com.example.cloudprovider.service.impl;

import com.example.cloudprovider.domain.UserInfo;
import com.example.cloudprovider.mapper.UserInfoMapper;
import com.example.cloudprovider.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserInfoMapper userMapper;

    @Override
    public UserInfo getUser(Integer userId) {
        return userMapper.getUser(userId);
    }
}

Controller

package com.example.cloudprovider.controller;

import com.example.cloudprovider.domain.UserInfo;
import com.example.cloudprovider.service.UserService;
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.RestController;

@RestController
public class UserInfoController {

    @Autowired
    private UserService userService;

    @GetMapping("user/{id}")
    public UserInfo getUser(@PathVariable("id") Integer userId) {
        return userService.getUser(userId);
    }
}

服務發布類

package com.example.cloudprovider;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.cloudprovider.mapper") //掃描Mapper類 註入到Spring容器中
public class CloudProviderApplication {

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

2.消費者(引入feign框架)

技術分享圖片

pom.xml

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

    <groupId>com.example</groupId>
    <artifactId>cloud-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>cloud-consumer</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.SR2</spring-cloud.version>
    </properties>

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

    <dependencies>
        <!-- 引入feign依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!--Service Discovery with Zookeeper-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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


</project>

application.yml

spring:
  cloud:
    zookeeper:
      connect-string: 192.168.3.201:2181
      discovery:
        register: false #不會註冊到zk中


provider: # 服務名稱
    ribbon: # 負載均衡實現依靠ribbon
      # 負載策略
      NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #隨機策略  其他策略百度

實體類

package com.example.cloudconsumer.vo;

import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Getter
@Setter
public class UserVO {
    private Integer userId;
    private String userName;
    private Date userBirth;
}

RestTemplate配置類

package com.example.cloudconsumer.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootConfiguration
public class RestTemplateConfiguration {

    @Bean
    @LoadBalanced // Ribbon 負載均衡
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Controller

package com.example.cloudconsumer.controller;

import com.example.cloudconsumer.vo.UserVO;
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.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class UserWarpController {
    @Autowired
    private RestTemplate restTemplate;

    // 調用只有一個或者多個服務實例API的情況下
    @GetMapping("warp/user/{userId}")
    public UserVO getUserData(@PathVariable("userId") Integer userId) {
        return restTemplate.getForObject("http://provider/user/"+userId, UserVO.class);
    }
}

使用框架的Controller

package com.example.cloudconsumer.controller;

import com.example.cloudconsumer.client.UserClient;
import com.example.cloudconsumer.vo.UserVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class UserFeignController {
    @Resource
    private UserClient userClient;

    // 調用只有一個或者多個服務實例API的情況下
    @GetMapping("feign/user/{userId}")
    public UserVO getUserData(@PathVariable("userId") Integer userId) {
        return userClient.getUserData(userId);
    }
}

feign調用客戶端

package com.example.cloudconsumer.client;

import com.example.cloudconsumer.vo.UserVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @FeignClient(name = "provider")
 * name為調用服務端的spring.application.name的值
 */
@FeignClient(name = "provider")
public interface UserClient {
    @GetMapping("user/{id}")
    public UserVO getUserData(@PathVariable("id") Integer userId);
}

服務啟動類:

package com.example.cloudconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient //可以發現ZK的服務
@EnableFeignClients //可以發現feign的服務
public class CloudConsumerApplication {

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

總結起來,feign框架可以理解成路由,對url進行再次包裝後供給客戶端調用,可以在這個路由上進行一系列限制操作,增強安全性。

SpingCloud之feign框架調用