springCloud 实现Feign自定义配置

新建一个统一管理工程

springCloud 实现Feign自定义配置_第1张图片

对应pom依赖:

<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.yb</groupId>
  <artifactId>microservicedemo</artifactId>
  <version>1.0</version>
  <packaging>pom</packaging>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
	</parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring-cloud.version>Finchley.M9</spring-cloud.version>    
  </properties>

 
  <modules>
  	<module>provider-user</module>
  	<module>consumer-order</module>
  	<module>eureka</module>
  	<module>consumer-order-ribbon</module>
  	<module>consumer-order-ribbon-config</module>
  	<module>consumer-order-ribbon-config2</module>
  	<module>consumer-order-ribbon-config-properties</module>
  	<module>eureka-ha</module>
  	<module>consumer-order-feign</module>
  	<module>consumer-order-feign-custom</module>
  </modules>
  
    <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- springBoot的依赖 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.2.3</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
    </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>
       <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- <configuration>
                    <mainClass>com.ooqiu.gaming.service.admin.GamingServerServiceAdminApplication</mainClass>
                </configuration> -->
            </plugin>
        </plugins>
    </build> 
</project>

eureka项目相关代码:

pom依赖:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.yb</groupId>
    <artifactId>microservicedemo</artifactId>
    <version>1.0</version>
  </parent>
  <groupId>com.eureka.yb</groupId>
  <artifactId>eureka</artifactId>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
       <!-- eurekaserver 依赖 -->
       <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <!-- <version>1.4.3.RELEASE</version> --> 
        </dependency>
        <!-- 安全依赖 -->
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
  </dependencies>
</project>

EurekaApp类代码:

package com.eureka.yb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableAutoConfiguration(exclude = {
        org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class
}) //排除安全配置,否则登录需要密码
@EnableEurekaServer // 声明这是一个Eureka Server
public class EurekaApp {
	public static void main(String[] args) {
		SpringApplication.run(EurekaApp.class);
	}
}

application配置:

server:
  port: 10000  #注册服务中心的端口号
eureka:
  instance:
    hostname: localhost
#    prefer-ip-address: true     
  client:
    register-with-eureka: false # 是否将自己注册到Eureka Server,默认为true。由于当前应用就是Eureka Server,故而设为false
    fetch-registry: false # 表示是否从Eureka Sever获取注册信息,默认为true。因为这一个单节点就是Eureka Server,不需要同步其他的Eureka Server节点的数据,故而设为false
    #hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000 
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka # 设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。 
#      defaultZone: http://user:123@${eureka.instance.hostname}:${server.port}/eureka #curl 风格 设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。 
#security:
#  basic:
#    enabled: true #开启安全配置,也就是需要密码,如果不需要密码设置为false即可,注意这个参数必须放在application.yml中,不允许放在bootstrap.yml   
#  user:
#    name: user
#    password: 123 #在配置了用户名密码后,我们可以修改地址的访问风格为 curl 风格

provider-user工程:
pom:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.yb</groupId>
    <artifactId>microservicedemo</artifactId>
    <version>1.0</version>
  </parent>
  <artifactId>provider-user</artifactId>
  <!-- <version>1.0</version> -->

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <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-client</artifactId>
        </dependency>
         <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency> 
  </dependencies>

</project>

application配置:

eureka:
  client:
    service-url:
    #http://localhost:8761/eureka/(即注册到的服务地址)
      defaultZone: http://localhost:10000/eureka
#      defaultZone: http://localhost:8762/eureka

#  instance:
#  # 将自己的IP注册到Eureka Server。若不配置或设置为false,表示注册微服务所在操作系统的hostname到Eureka Server
#    prefer-ip-address: true 
server:
  port: 7900 #程序启动后的端口,也就是tomcat的端口,我们可以自己定义
spring:
  application:
  # 指定注册到Eureka Server上的应用名称
    name: provider-user 

Provider类:

package com.yb.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;


@SpringBootApplication
@EnableEurekaClient//启用 eureka 客户端
public class Provider {
	public static void main(String[] args) {
		SpringApplication.run(Provider.class);
	}
}

UserController类:

package com.yb.provider.springcloud.controller;

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 com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.yb.provider.springcloud.pojo.User;

@RestController
public class UserController {
	@Autowired
	private EurekaClient eurekaClient;
	@GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
    	return new User(id);
    }
	@GetMapping("/info")
    public String info() {
        InstanceInfo instance = eurekaClient.getNextServerFromEureka("PROVIDER-USER", false);
        return instance.getHomePageUrl();
	}
	@GetMapping("/get-user")
	public User getUser(User user) {
		return user; //相当于传递一个复杂参数会被封装成user对象,然后将封装对象返回
	}
}

User类:

package com.yb.provider.springcloud.pojo;

import java.util.Date;

public class User {
	private Long id;
	private Date date;

	public User(Long id) {
		this.id = id;
		this.date = new Date();
	}

	public User() {

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

}

consumer-order-feign-custom工程:
pom依赖:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.yb</groupId>
    <artifactId>microservicedemo</artifactId>
    <version>1.0</version>
  </parent>
  <artifactId>consumer-order-feign-custom</artifactId>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
	<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-client</artifactId>
        </dependency>
         <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
		    <groupId>org.springframework.cloud</groupId>
		    <artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency> 
	</dependencies>
</project>

application配置:

eureka:
  client:
    service-url:
    #http://localhost:8761/eureka/(即注册到的服务地址)
      defaultZone: http://localhost:10000/eureka
# instance:
  # 将自己的IP注册到Eureka Server。若不配置或设置为false,表示注册微服务所在操作系统的hostname到Eureka Server,true则为ip
  # prefer-ip-address: false 
server:
  port: 8900
spring:
  application:
    name: consumer-order 
user:
  url: http://localhost:7900/user/    
 

自定义feign的两种实现方式:
OrderConsumer代码块:

package com.yb.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
 * feign 的英文表意为“假装,伪装,变形”, 是一个http请求调用的轻量级框架,
 * 可以以Java接口注解的方式调用Http请求,而不用像Java中通过封装HTTP请求报文的方式直接调用
 * @author yb
 *
 */
@SpringBootApplication
@EnableEurekaClient//启用 eureka 客户端
@EnableFeignClients//启用feign客户端
public class OrderConsumer {
	public static void main(String[] args) {
		SpringApplication.run(OrderConsumer.class);
	}

	@Bean // 把rest模板注册到bean容器,相当于xml中bean标签,主要用于调用当前方法获取到指定对象
	// @LoadBalanced//支持负载均衡
	RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

OrderController代码块:

package com.yb.consumer.springcloud;

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;

import com.yb.consumer.springcloud.feign.FeignClient01;
import com.yb.consumer.springcloud.feign.FeignClient2;
import com.yb.consumer.springcloud.pojo.User;


@RestController
public class OrderController {
	@Autowired
    private FeignClient01 feignClient01;
	@Autowired
    private FeignClient2 feignClient02;
	
	@GetMapping("/order/{id}")
    public User getOrder(@PathVariable Long id) {
		User user = feignClient01.getOrder(id);
		return user;
	}
	@GetMapping("/get-user")
    public User getOrder(User user) {
		User order = feignClient01.get_user(user);
		return order;
	}
	@RequestMapping("/serviceifo/{name}")
	public String getServiceInfo(@PathVariable String name) {
		return feignClient02.getServiceInfo(name);
	}
	@GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
		User user = feignClient02.getOrder(id);
		return user;
	}
}

FeignClient01Config代码块:

package com.yb.consumer.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.Contract;
@Configuration
public class FeignClient01Config {
	 @Bean
     public Contract feignContract() {
    	 return new feign.Contract.Default();
     }
}

FeignClient02Config代码块:

package com.yb.consumer.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.Contract;
import feign.auth.BasicAuthRequestInterceptor;
@Configuration
public class FeignClient02Config {
	 @Bean
     public Contract feignContract() {
    	 return new feign.Contract.Default();
     }
	/**
	 * 指定用户名和密码,用于创建用户名和密码的对象,密码加不加都无所谓,因为已经在启动时排除
	 * @return
	 */
//	 @Bean
//     public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
//    	 return new BasicAuthRequestInterceptor("user","123");
//     }
}

User代码块:

package com.yb.consumer.springcloud.pojo;

import java.util.Date;

public class User {
	private Long id;
	private Date date;

	public User(Long id) {
		this.id = id;
		this.date = new Date();
	}

	public User() {

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

}

FeignClient01代码块:

package com.yb.consumer.springcloud.feign;

import org.springframework.cloud.openfeign.FeignClient;
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.RequestMethod;

import com.yb.consumer.config.FeignClient01Config;
import com.yb.consumer.springcloud.pojo.User;

import feign.Param;
import feign.RequestLine;

@FeignClient(name = "provider-user",configuration = FeignClient01Config.class)
public interface FeignClient01 {
//	@GetMapping("/user/{id}")
//	@RequestMapping(value="/user/{id}",method = RequestMethod.GET)
	@RequestLine("GET /user/{id}")//组合注解,第一个是请求方式,第二个是参数,用空格分割,如果使用了feign自己的注解,则整个接口必须全部使用这种方式,否则报错
    User getOrder(@Param("id") Long id);//注意必须加@PathVariable("id")注解,如果使用feign自己注解@RequestLine,@PathVariable("id")改为feign自己的@Param注解,否则请求失败
//	@GetMapping("get-user")//无法访问,提供者必须是post接口才能被访问,如果必须使用get传递多个参数,只能使用普通方式,不能封装为复杂对象
//	@RequestMapping(value="/get-user",method = RequestMethod.GET)
	@RequestLine("GET /get-user")
	User get_user(User user);//如果传递的是复杂参数,那么 Feign 不管配置的是什么请求方式,都会以post方式发出去
}

FeignClient2代码块:

package com.yb.consumer.springcloud.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yb.consumer.config.FeignClient02Config;
import com.yb.consumer.springcloud.pojo.User;

import feign.Param;
import feign.RequestLine;




/**
 * 使用url访问方式
 * @author yb
 *
 */
//@FeignClient(name = "yb",url = "http://localhost:10000/",configuration = FeignClient02Config.class)
@FeignClient(name = "yb",url = "http://localhost:7900",configuration = FeignClient02Config.class)
public interface FeignClient2 {
   @RequestLine("GET eureka/apps/{servicename}")
//   @RequestMapping("eureka/apps/{servicename}")
   String getServiceInfo(@Param("servicename") String servicename);
	
   @RequestLine("GET /user/{id}")//组合注解,第一个是请求方式,第二个是参数,用空格分割,如果使用了feign自己的注解,则整个接口必须全部使用这种方式,否则报错
    User getOrder(@Param("id") Long id);
}

运行效果如下:
springCloud 实现Feign自定义配置_第2张图片

springCloud 实现Feign自定义配置_第3张图片

springCloud 实现Feign自定义配置_第4张图片
springCloud 实现Feign自定义配置_第5张图片

你可能感兴趣的:(springCloud,实现Feign自定义配置)