使用springcloud搭建简单的微服务

1、eureka server 注册中心创建

(1)创建maven工程

(2)创建注册中心springboot模块,选择需要导入的包 

(3)配置文件里面添加eureka配置

#设置服务器端口
server.port:9000
#设置应用程序名称  名字不许用下划线,不支持服务调用
spring.application.name=eureka-server-demo
#主机地址
eureka.instance.hostname=localhost
#表示不向注册中心注册
eureka.client.register-with-eureka=false
#表示不向注册中心调用服务
eureka.client.fetch-registry=false
#服务的地址
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka

(4)启动类上添加开启eureka服务注解

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerDemoApplication {

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

}

(5) 启动应用,在浏览器输入启动地址:http://localhost:9000/,看到以下页面,说明eureka注册中心配置成功

2、生产者服务创建

 (1)创建eureka服务生产者springboot工程,并添加需要导入的组件jar包

(2) 配置文件中添加配置

#服务器端口
server.port=9001
#配置发布服务地址
spring.application.name=sp-provider-demo
eureka.client.service-url.defaultZone=http://localhost:9000/eureka

(3)启动类添加开启eureka服务的注解

@EnableEurekaClient
@SpringBootApplication
public class SpProviderDemoApplication {

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

}

 (4)编写一个简单的测试类

@RestController
public class TestController {
    @RequestMapping("/getData")
    public String getData(){
        return "这只是一个简单的测试方法";
    }
}

(5)启动服务,在浏览器输入自己配置的启动地址:http://localhost:9001/getData,有返回数据,说明服务启动成功 ,eureka管理界面也能看到我们启动的服务,说明成功注册上去

3、消费者服务创建

(1) 创建一个消费者springboot工程,步骤跟生产者工程的创建一致

(2)修改配置文件

#服务器
server.port=9002
#服务的名称
spring.application.name=sp-consumer-demo
#指定注册中心:eureka服务器
eureka.client.service-url.defaultZone=http://localhost:9000/eureka

(3)启动类添加开启eureka服务的注解

@EnableEurekaClient
@SpringBootApplication
public class SpConsumerDemoApplication {

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

    @Bean   //交给spring容器管理
    @LoadBalanced  // 支持使用服务名称发现服务进行调用,且支持负载
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

(4)编写一个调用生产者服务的测试类

@RestController
public class ConsumerTestController {
    @Autowired
    private RestTemplate restTemplate; // 从spring容器自动注入RestTemplate对象
    @RequestMapping("showData")
    public String showData(){
        String stu = restTemplate.getForObject("http://SP-PROVIDER-DEMO/getData", String.class);
        return stu;
    }
}

 (5)启动消费者服务,浏览器打开自己的地址:http://localhost:9002/showData,出现结果,说明消费成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值