Spring cloud 学习(一)--eureka的server和client

本文详细介绍如何使用Spring Cloud Eureka实现服务注册与发现。包括搭建Eureka Server、配置服务提供者并将其注册到Eureka Server的过程。通过具体代码和配置示例,展示了如何创建Eureka Server和Client,以及如何在服务间进行相互调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本博客的参考文章:https://www.fangzhipeng.com/springcloud/2017/06/01/sc01-eureka.html

一、server端的配置

右键工程->创建model-> 选择spring initialir 如下图:

点击next,配置好文件名等基本内容,继续下一步,选择Spring cloud Discovery-->server

这样就创建完成一个server,client同理

在springboot工程的启动application类上加@EnableEurekaServer,该注解是指启动一个服务注册中心

package com.xtc.springcloudserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class SpringCloudServerApplication {

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

}

配置application.properties配置文件,用yml格式的也可以,选择自己喜欢的方式。

server.port=8761
eureka.instance.hostname=localhost
//eureka.client.registerWithEureka:false和fetchRegistry:false来表明自己是一个eureka server.
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

最后看一下效果:访问:http://localhost:8761/

 

二、创建一个服务提供者 (eureka client)

 

创建模块的方式同上,要加上一个web的选项方便测试,否则就需要自己添加web的依赖

启动类代码

package com.xtc.springcloudclient;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableEurekaClient//表明自己是EurekaClient
public class SpringCloudClientApplication {

    @Value("${server.port}")
    private String port;

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

    @GetMapping("/hi")
    public String f(@RequestParam String name){
        return "hi "+name+",i am from port:" +port;
    }
}

配置文件的内容 

#注明自己的服务注册中心的地址
eureka.client.service-url.defaultZone= http://localhost:8761/eureka/
#自身端口号
server.port=8762
#以后的服务与服务之间相互调用一般都是根据这个name
spring.application.name=service-first

 

启动项目测试一下,记住先启动server,在启动client,不然会报错:

访问:http://localhost:8762/hi?name=heihiehie

hi heihiehie,i am from port:8762

访问:http://localhost:8761

 

结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值