1、引入必要的maven依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath />
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
</dependencies>
2、创建springboot的启动类:
@SpringBootApplication
@EnableDiscoveryClient
public class HelloApplicaton {
//这里就是创建一个负载均衡的RestTemplate Bean
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(HelloApplicaton.class, args);
}
}
3、resource下配置启动文件:application.yml或者application.properties
server:
port: 9091
spring:
application:
name: post-service
eureka:
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://localhost:1111/eureka/
4、创建消费者请求接口:
@RestController
public class HelloController {
//注入前面创建的负载均衡的RestTemplate
@Autowired
public RestTemplate restTemplate;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String postHello(){
//使用有负载均衡能力的RestTemplate请求微服务
return restTemplate.getForEntity("http://HELLO-SERVICE/hello"
,String.class,"").getBody();
}
}
注:这里的HELLO-SERVICE就是注册中心存在的微服务的名称,这个大家应该都很清楚;
这样一个具有负载均衡能力的消费者接口就创建成功了!
网友评论