分布式--服务发现与消费者

参照自己上篇写:服务注册

服务发现与消费者

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

效果图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值