SpringCloud学习笔记-Eureka的服务拉取

假设是OrderService里面拉取Eureka的服务之一User Service

1.依然需要在该服务里面引入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2.在OrderService里面需要有如下配置

yml 复制代码
spring:
  application:
    name: orderservice #添加的微服务的服务名称,把名字为userservice的微服务加入到注册名单中
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka   #eureka的地址信息

3.修改URL和OrderService中添加@Load Balanced注解

1.修改URL

java 复制代码
package cn.itcast.eureka.order.service;

import cn.itcast.eureka.order.mapper.OrderMapper;
import cn.itcast.eureka.order.pojo.Order;
import cn.itcast.eureka.order.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;
    public Order queryOrderById(Long orderId) {

        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        String url = "http://userservice/user/" + order.getUserId();//OrderService里面拉取Eureka的服务之一User Service
        //把原来的http://localhost:8080/user/变成了http://userservice/user/
        User user = restTemplate.getForObject(url, User.class);
        order.setUser(user);
        // 4.返回
        return order;
    }
}

2.OrderService中添加@Load Balanced注解

java 复制代码
package cn.itcast.eureka.order;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@MapperScan("cn.itcast")
@SpringBootApplication
public class OrderApplication {
    @Bean @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

}

通过服务名称获取IP地址的原理如下图所示,其中由于WIndows电脑的设置,原来的IP地址被替换成为了电脑名称LAPTOPXXX,其实还是可以获取到具体的IP

相关推荐
RainCity3 天前
Java Swing 自定义组件库分享(十二)
java·笔记·后端
吃饱了得干活3 天前
Spring Cloud Gateway 微服务网关:路由、断言、过滤器
java·spring cloud
LinXunFeng10 天前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
通信小呆呆14 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick14 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee14 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn8614 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
YM52e14 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨14 天前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
闪闪发亮的小星星14 天前
高斯光以及高斯光公式解释
笔记