Eureka + Ribbon + RestTemplate 负载均衡
Step 5-1:使用 Spring Initializr 创建 Spring Boot 项目
选择如下配置
Step 5-2:创建配置文件 application.yml,内容如下
server:
port: 8764
spring:
application:
name: service-ribbon
#如果没有eureka下边配置不用写
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
Step 5-3:编写启动类 @EnableDiscoveryClient
注意:通过@EnableDiscoveryClient向服务中心注册;
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
Step 5-4:编写Service
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
}
}
Step 5-5:编写Contorller @RestController
/**
* Created by fangzhipeng on 2017/4/6.
*/
@RestController
public class HelloControler {
@Autowired
HelloService helloService;
@RequestMapping(value = "/hi")
public String hi(@RequestParam String name){
return helloService.hiService(name);
}
}
启动后效果:访问 http://localhost:8764/hi?name=forezp
浏览器交替显示:
hi forezp,i am from port:8762
hi forezp,i am from port:8763