首页 > 其他 > 详细

微服务:Eureka快速入门!

时间:2020-10-28 14:20:13      阅读:37      评论:0      收藏:0      [点我收藏+]

一、服务治理与负载均衡

搭建服务治理服务器——Eureka服务器

导入依赖:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

编写配置文件

server:
  port: 8761 #服务端口号

eureka:
  client:
    register-with-eureka: false #由于当前Eureka应用为服务端,因此设置当前用户不进行注册。防止自己向自己注册发生异常
    fetch-registry: false       #由于注册中心主要是维护管理实例,因此它并不需要去检索服务实例,因此也设置为false
  server:
    enable-self-preservation: true

主启动类:@EnableEurekaServer

到目前为止,我们的服务治理服务器Eureka就搭建完成了!

搭建服务提供者——注册服务

导入依赖

		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

编写配置文件

server:
  port: 1234          #配置端口号
eureka:
  instance:
    appname: fwz   #配置客户端在Eureka服务器端中的名称
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/  #设置向注册中心注册服务的地址
spring:
  application:
    name: fwz

主启动类:@EnableDiscoveryClient

到目前为止,我们就完成了服务的注册!

搭建服务消费者——服务消费

package com.botao.eurekaxfz;

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;

@SpringBootApplication
@EnableDiscoveryClient
public class EurekaXfzApplication {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(EurekaXfzApplication.class, args);
    }

}

package com.botao.eurekaxfz.controller;


import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RequestMapping(path = "/api")
@RestController
public class TestController {

    @Autowired
    RestTemplate restTemplate;
    @GetMapping("hello")
    public String hello(){
        return restTemplate.getForObject("http://fwz/api/hello",String.class);
    }
}

微服务:Eureka快速入门!

原文:https://www.cnblogs.com/botaoJava/p/13890275.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!