Eureka服务

Eureka服务

  1. 搭建EurekaServer
  2. 服务注册
  3. 服务发现

image-20240109122336252

需要有一个注册服务的module。
引入maven依赖,添加server启动类注解,注册url和端口号之后,服务端搭建完成。

<!--eureka服务端-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
server:
  port: 10086 #服务端口
spring:
  application:
    name: eurekaserver #服务名称
eureka:
  client:
    service-url: # eureka地址信息
      defaultZone: http://127.0.0.1:10086/eureka
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }
}

其他模块如果需要使用微服务调用http请求获取其他服务的功能,需要先在eureka服务端进行注册,然后即可通过eureka调用其他模块的服务。注册的步骤是,引入依赖,再添加注册配置信息。

<!--eureka客户端依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
spring:
  application:
    name: orderservice #服务名称
eureka:
  client:
    service-url: # eureka地址信息
      defaultZone: http://127.0.0.1:10086/eureka
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    /**
     * 创建RestTemplate对象,注入spring容器
     * @return
     */
    @Bean
    @LoadBalanced //负载均衡
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
public Order queryOrderById(Long orderId) {
    // 1.查询订单
    Order order = orderMapper.findById(orderId);
    // 2.利用restemplate发起http请求,查询用户
    // 2.1 url路径
    String url = "http://userservice/user/" + order.getUserId();
    // 2.2 发送http请求,实现远程调用
    User user = restTemplate.getForObject(url, User.class);
    // 3.封装user对象到order
    order.setUser(user);
    // 4.返回
    return order;
}
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值