本文主要是介绍springcolud-服务消费者,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.pom文件添加服务消费者的起步依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId></dependency>
</dependencies>
2.配置eureka消费地址
server.port=8088spring.application.name=consspring.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka_server/
3.启动类注解@EnableEurekaClient,并将restTemplate注入到ioc容器,并使用@LoadBalanced注解声明开启负载均衡
package com.kejin.cons;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
@EnableEurekaClient
public class EurekaConsApplication {public static void main(String[] args) {SpringApplication.run(EurekaConsApplication.class, args);}@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}}
4.测试,编写一个controller,注入RestTemplate用其调用服务提供者接口
package com.kejin.cons.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;@RestController
public class RibbonController {@AutowiredRestTemplate restTemplate;@GetMapping("/getPortInfo")public String getPoducerInfo() {String result = this.restTemplate.getForObject("http://service-eureka-clienteureka/getPortInfo", String.class);return result;}
}
这篇关于springcolud-服务消费者的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!