1.使用Eureka组件创建服务中心Server_1
@EnableEurekaServer //表示自己是一个server
@SpringBootApplication
public class EurekaserverApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaserverApplication.class, args);
}
}eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: service-ribbon通过eureka.client.registerWithEureka:false和fetchRegistry:false来表明自己是一个eureka server.
2.使用Eureka组件创建客服端Clinet_P_1,Clinet_P_2,即P表示生产者,服务提供者。并且指定服务中心的地址Server_1。
@SpringBootApplication
@EnableEurekaClient //表示自己是一个client
@RestController
public class ServiceHiApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHiApplication.class, args);
}
@Value("${server.port}")
String port;
@RequestMapping("/hi")
public String home(@RequestParam String name) {
return "hi "+name+",i am from port:" +port;
}
}3.使用ribbon组件创建客户端Client_C_1,C表示customer,服务消费者,并且指定服务中心的地址Server_1。
创建主类@SpringBootApplication
@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}调用远程服务
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
}
}配置文件
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: service-ribbon参考: http://blog.youkuaiyun.com/forezp/article/details/69788938
http://blog.youkuaiyun.com/forezp/article/details/69696915
本文介绍如何使用Eureka组件搭建服务中心(Server_1)并实现服务注册与发现,同时展示如何创建服务提供者(Clinet_P_1, Clinet_P_2)和服务消费者(Client_C_1),通过Ribbon组件实现负载均衡。
456

被折叠的 条评论
为什么被折叠?



