微服务初体验,微服务学习之创建服务消费者(springcloud)

上上篇文章我们介绍了微服务注册中心的创建,以及详细讲解,链接如何搭建注册中心

https://blog.csdn.net/qq_41426763/article/details/101049964

上篇文章我们介绍了微服务提供者的创建,以及详细讲解,链接如何创建提供者

https://blog.csdn.net/qq_41426763/article/details/101106379

这篇文章我们来介绍一下服务消费者:

SpringCloud服务消费有2种方式,第一种:Feign 第二种:RestTemplate+Ribbon
Feign是一种声明式、模板化的HTTP客户端,可以进行网络请求
Feign 实现步骤

1、依赖jar
<dependency> 
<groupId>org.springframework.cloud</groupId> 
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
 <dependency>
  <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId> 
   </dependency>
2、编写代码

编写接口

@FeignClient("HelloProvider") 
public interface HelloService { 
	@GetMapping("/provider/hello/first.do") 
	String hello(); 
}

编写控制器

@RestController
 public class HelloController {
 	 @Autowired
     private HelloService helloService; @GetMapping("/api/hello/first.do")
     public String hello(){
    	 return helloService.hello(); 
     } 
  }
3、配置开关类

使用

@EnableDiscoveryClient //发现服务 
@EnableFeignClients //基于Feign实现服务消费

@SpringBootApplication 
@EnableDiscoveryClient //注册并发现服务 
@EnableFeignClients //启用Feign 进行服务消费 
@EnableSwagger2 
public class HelloApplication { 
	public static void main(String[] args) { 
		SpringApplication.run(HelloApplication.class,args); 
	} 
}
4、配置全局配置文件
eureka: 
	client: 
		serviceUrl: 
			defaultZone: http://localhost:8761/eureka/ 
server: 
	port: 9902 
spring: 
	application: 
		name: HelloConsumer
5、运行并测试

在这里插入图片描述

发布了20 篇原创文章 · 获赞 36 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41426763/article/details/101157474
今日推荐