栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Cloud学习笔记.实现第一个微服务系统(服务消费者Consumer,Feign)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Cloud学习笔记.实现第一个微服务系统(服务消费者Consumer,Feign)

实现服务消费者
  • 创建项目与服务提供者一样。
  • 添加依赖


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.5.5
		 
	
	com.example
	demo
	0.0.1-SNAPSHOT
	Eureka Consumer Demo
	Demo project for Spring Boot
	
		1.8
		2020.0.4
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.cloud
			spring-cloud-starter-netflix-eureka-client
		

		
			org.springframework.cloud
			spring-cloud-starter-openfeign
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	
	
		
			
				org.springframework.cloud
				spring-cloud-dependencies
				${spring-cloud.version}
				pom
				import
			
		
	

	
		
			
				org.apache.maven.plugins
				maven-resources-plugin
				3.1.0
			

			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	



配置资源文件application.properties

#“服务消费者”的名称
spring.application.name=consumer
#服务消费者的端口号
server.port=9000
#不注册到服务中心
eureka.client.register-with-eurek=false
#服务中心地址
eureka.client.serviceUrl.defaultZone=http://node1:8081/eureka/,http://node2:8082/eureka/,http://node3:8083/eureka/

在启动类中,添加注解以启用客户端的服务注册和发现功能

package com.example.demo;

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

//启用Feign的远程服务调用RPC
@EnableFeignClients

public class EurekaConsumerDemoApplication {

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

}

调用“服务提供者”接口

Feign是一个声明式Web Service客户端,使用Feign能让编写Web Service客户端更加简单,具体步骤为:

  • 添加Feign的依赖
  • 在启动类中加入注解@EnableFeignClients
  • 定义一个接口,在该接口中添加注解以使用它。
package com.example.demo;


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

@FeignClient(name="provider")
public interface MmqFeignClient {
    @RequestMapping(value = "/hello")
    public String hello();
}

实现客户端接口
package com.example.demo.controller;

import com.example.demo.MmqFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



@RestController
public class ConsumerController {
    //注入接口
    @Autowired
    MmqFeignClient mfCli;
    @RequestMapping("/hello")
    public String index(){
        //返回内容
        return mfCli.hello();
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/284950.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号