ribbon服務端
1.pom依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
2.啓動類
在啓動類中注入bean對象
@Bean
@LoadBalanced// 通過這個註解,即可實現ribbon的負載均衡
public RestTemplate template(){
return new RestTemplate();
}
3.配置文件
server:
port: 8092
###定義實例名
spring:
application:
name: spring-cloud-ribbon-consumer
##禁止向eureka註冊
eureka:
client:
enabled: false
##脫離eureka來完成服務調用測試(ribbon會默認去註冊中心去獲取服務地址)
helloclient:
ribbon:
listOfServers: localhost:8001,localhost:8002
測試
創建2個一樣的hello-demo服務,修改端口號
1.hello-demo的controller層
@RestController
public class HelloController {
@Value("${name}")
private String name;
@Value("${age}")
private int age;
@Value("${password}")
private String password;
@Autowired
private HelloService helloService;
@GetMapping("")
public Object index(){
return new Teacher(this.name, this.age, this.password);
}
@GetMapping("user")
public Object getUser(@Param("id")String id){
System.out.println("客戶端1返回了請求");
//System.out.println("客戶端2返回了請求"); //第二個服務的打印信息
return helloService.get(id);
}
@PostMapping("get-teacher")
public String postForTeacher(@RequestBody Object msg){
return msg.toString();
}
}
ribbon服務端的Controller層
@RestController
public class ConsumerController {
@Autowired
RestTemplate restTemplate;
@GetMapping("")
public Object index(@RequestParam("id")String id){
//localhost:8001和http://helloclient等同 ,在配置文件中有相關配置
// return restTemplate.getForObject("http://localhost:8001/user?id="+id+"",Object.class);
return restTemplate.getForObject("http://helloclient/user?id="+id+"",Object.class);
}
@GetMapping("/get-teacher")
public Object getTeacher(){
// return restTemplate.getForEntity("http://localhost:8001",Teacher.class);
return restTemplate.getForEntity("http://helloclient",Teacher.class);
}
}
啓動服務
訪問http://localhost:8092/?id=1
第一次,第一個HelloDemo返回了請求信息,第二個沒有
第二次訪問
第一個hello-demo沒有返回信息,第二個返回了
可以看到,ribbon生效了
示例代碼:
碼雲