服务发现与消费者
1、在消费者工程consumer-user的java目录下创建contrller层
创建UserController类
UserController.java
package controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/buy")
public String buyTicket(String name){
return name+"购买了";
}
}
2、在application.yml配置参数
spring:
application:
name: consumer-user
server:
port: 8200
eureka:
instance:
prefer-ip-address: true # 注册服务的时候使用服务的ip地址
client:
service-url:
defaultZone: http://localhost:8761/eureka/
当我们需要启动服务的时候,需要在消费者的主程序添加一个注解@EnableDiscoveryClient ,这个注解是开启发现服务功能!
当我们还需要用载均衡机制将服务注册进来,需要运用到:
@LoadBalanced //使用负载均衡机制
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
就可以在controller层下的UserController类编写获取数据
String s = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class);
UserController类代码如下:
UserController.java
package 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.RestTemplate;
@RestController
public class UserController {
@Autowired
RestTemplate restTemplate;
@GetMapping("/buy")
public String buyTicket(String name){
String s = restTemplate.getForObject("http://PROVIDER-TICKET/ticket", String.class);
return name+"购买了";
}
}
消费者的主程序代码如下:
ConsumerUserApplication.java
package com.study.consumeruser;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* 服务消费者
*/
@EnableDiscoveryClient //开启发现服务功能
@SpringBootApplication
public class ConsumerUserApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerUserApplication.class, args);
}
@LoadBalanced //使用负载均衡机制
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
启动消费者的主程序,控制台日志打印信息:
访问注册中心的页面刷新:
localhost:8761
效果图: