需要jar包
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
启动文件
package com.example.ribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
创建配置文件
@Configuration
public class RibbinConfig {
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
创建一个serice
@Service
public class RibbonService {
@Autowired
RestTemplate restTemplate;
public String hi(){
/*
地址必须是注册的名字
http://eureka-client:8888/hi 提前创建好的client
*/
return restTemplate.getForObject("http://eureka-client:8888/hi",String.class);
}
}
控制器
@RestController
public class RibbonController {
@Autowired
RibbonService ri;
@RequestMapping("/hi")
/*
测试负载均衡 和熔断器
*/
public String hi(){
return ri.hi();
}
}