Eureka(F版本)教程二 服务消费者

service-ribbon

0.0.1-SNAPSHOT

service-ribbon

jar

Demo project for Spring Boot

1.8

Greenwich.SR2

org.springframework.cloud

spring-cloud-starter-netflix-eureka-client

org.springframework.boot

spring-boot-starter-web

org.springframework.cloud

spring-cloud-starter-netflix-ribbon

org.springframework.boot

spring-boot-maven-plugin

在工程的配置文件指定服务的注册中心地址为http://localhost:8761/eureka/,程序名称为 service-ribbon,程序端口为8764。配置文件application.yml如下:

eureka:

client:

serviceUrl:

defaultZone: http://localhost:8761/eureka/

server:

port: 8764

spring:

application:

name: service-ribbon

在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。

package com.loren.serviceribbon;

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.cloud.netflix.eureka.EnableEurekaClient;

import org.springframework.context.annotation.Bean;

import org.springframework.web.client.RestTemplate;

/**

  • @author

  • 在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;

  • 并且向程序的ioc注入一个bean: restTemplate;

  • 并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。

    */

    @SpringBootApplication

    @EnableEurekaClient

    @EnableDiscoveryClient

    public class ServiceRibbonApplication {

    public static void main(String[] args) {

    SpringApplication.run(ServiceRibbonApplication.class, args);

    }

    @Bean

    @LoadBalanced

    RestTemplate restTemplate() {

    return new RestTemplate();

    }

    }

    写一个测试类HelloService,通过之前注入ioc容器的restTemplate来消费service-hi服务的“/hi”接口,在这里我们直接用的程序名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名,代码如下:

    package com.loren.serviceribbon.service;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.stereotype.Service;

    import org.springframework.web.client.RestTemplate;

    @Service

    public class HelloService {

    先自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

    深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

    因此收集整理了一份《Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

    由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

    如果你觉得这些内容对你有帮助,可以扫码领取!

    最后

    码字不易,觉得有帮助的可以帮忙点个赞,让更多有需要的人看到

    又是一年求职季,在这里,我为各位准备了一套Java程序员精选高频面试笔试真题,来帮助大家攻下BAT的offer,题目范围从初级的Java基础到高级的分布式架构等等一系列的面试题和答案,用于给大家作为参考

    以下是部分内容截图

    =“img” style=“zoom: 33%;” />

    最后

    码字不易,觉得有帮助的可以帮忙点个赞,让更多有需要的人看到

    又是一年求职季,在这里,我为各位准备了一套Java程序员精选高频面试笔试真题,来帮助大家攻下BAT的offer,题目范围从初级的Java基础到高级的分布式架构等等一系列的面试题和答案,用于给大家作为参考

    以下是部分内容截图

    [外链图片转存中…(img-pIjZMXLj-1711365768089)]

    需要更多Java资料的小伙伴可以帮忙点赞+关注,点击传送门,即可免费领取!