开发者学堂课程【SpringBoot 快速掌握 - 高级应用:服务发现 &;消费】学习笔记,与课程紧密联系,让用户快速学习知识
课程地址:https://developer.aliyun.com/learning/course/613/detail/9321
服务发现 &;消费
内容介绍
一、编写一个简单的处理请求
二、在注册中心里发现服务
三、启动消费者并测试
一、编写一个简单的处理请求
1.新建名为 controller.UserController 的类
新建一个类,名为 controller.UserController:
p
ackage
com.atguigu.consumeruser.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
RestController;
@ RestController
public class UserController{
@GetMapping(“/buy”)
public String buyTicket(String name ){
return name+”购买了“+”s;
/“+”上名字
}
}
2.进行配置
在 resources 中使用 yml,新建一个文件,名为 application.yml
//这个层次更清晰
spring:
application:
name:consumer-user //当前应用的名字
//这里应用的名字,最终会落实到注册中心的 Application 上
同时演练访问端口
server:
port:8200
eureka:
instance:
prefer-ip-address:true //注册服务时使用ip地址
client:
service-url:
defaultZone:http://localhost:8761/eureka/
会发现当前应用也能注册到注册中心当中
二、在注册中心里发现服务
1.添加注解 EnableDiscoveryClient
package com.atguigu.consumeruser.controller;
import org.springframework.web.bind.annotation;
@EnableDiscoveryClient
//开启发现服务功能
@SpringBootApplication
public class ConsumerUserApplication {
public static void main(String[ ] args) {
SpringApplication. run(ConsumerUserApplication.class, args);
}
2.结合 RestTemplate
package com.atguigu.consumeruser.controller;
import org.springframework.web.bind.annotation;
@EnableDiscoveryClient
//开启发现服务功能
@SpringBootApplication
public class ConsumerUserApplication {
public static void main(String[ ] args) {
SpringApplication. run(ConsumerUserApplication.class, args);
}
@Bean
public RestTemplate restTemplate( ) {
return new RestTemplate( );
}
}
3.使用负载均衡机制
package com.atguigu.consumeruser.controller;
import org.springframework.web.bind.annotation;
@EnableDiscoveryClient
//开启发现服务功能
@SpringBootApplication
public class ConsumerUserApplication {
public static void main(String[ ] args) {
SpringApplication. run(ConsumerUserApplication.class, args);
}
@LoadBalanced
//使用负载均衡机制
@Bean
public RestTemplate restTemplate( ) {
return new RestTemplate( );
}
}
4.消费服务
package com.atguigu.consumeruser.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemple;
@RestController
public class Ticketcontroller {
@Autowired
RestTemplate restTemplate;
//注册
@GetMapping(“/buy”)
//调用 buy
public String buyTicket(String name ){
//请求的时候,调用名字就可以返回
restTemplate.getForObject(url:”http://PROVIDER-TICKET/ticket,String.class”)
//获取
return name+”购买了“+”s;
}
}
三、启动消费者并测试
启动 ConsumerUserApplication,显示端口8200已启动成功,返回注册中心刷新,会发现 Consumer-User 也注册成功了。接着通过192.168.0.104:8200/buy 访问端口8200的 buy 方法。
运行显示:null 购买了《厉害了,我的国》。说明此时 name 为空,传一个 name,192.168.0.104:8200/buy?name= 张三。其中《厉害了,我的国》是从注册中心PROVIDER-TICKET 的实例来调用的,且其为负载均衡体制。访问任意一个都是有均衡体制的。
注意:买票时会使用 restTemplate 来请求远程的 PROVIDER-TICKET 来获取门票。