注册中心Eureka:
每一个实例注册进Eureka后向他发送心跳,如果心跳超时,通常Eureka会删除该服务.
//启动类:
@SpringBootApplication
@EnableEurekaServer //关键
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run( EurekaServerApplication.class, args );
}
}
通过eureka.client.registerWithEureka:false和fetchRegistry:false来表明自己是一个eureka server,
不然启动会端口冲突报错,如果两台Eureka组成高可用的话,就不用配置为false.
//配置:
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
spring:
application:
name: eureka-server
服务提供者:
启动两台服务提供者即可搭建服务集群,通过ribbon可实现负载均衡访问这两台服务提供者.
//启动类
@SpringBootApplication
@EnableEurekaClient //关键
@RestController
public class ServiceHiApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHiApplication.class, args);
}
@Value("${server.port}") //注入配置文件字段
String port;
@RequestMapping("/client_hi")
public String home(@RequestParam String name) {
return "hi "+name+",i am from port:" +port;
}
}
//配置:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/ //声明注册中心地址
server:
port: 8762
spring:
application:
name: service-client //声明服务名,将来使用这个服务时根据服务名调用
服务消费方
Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。
Feign默认集成了ribbon
先讲解下基于ribbon+rest
//启动类
@SpringBootApplication
@EnableDiscoveryClient //关键
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean //向Spring仓库注入一个bean: restTemplate
@LoadBalanced //表明这个restRemplate开启客户端负载均衡的功能
RestTemplate restTemplate() {
return new RestTemplate();
}
}
//配置:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/ //指定注册中心地址以发现服务
server:
port: 8764
spring:
application:
name: service-ribbon //声明服务名
//应用代码
//service层
@Service
public class HelloService {
@Autowired //注入启动类中的实例
RestTemplate restTemplate;
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-CLIENT/client_hi?name="+name,String.class);
}
}
//controller层
@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.调用成功
Feign:整合了Ribbon,默认开启负载均衡
//启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients //关键
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
//应用代码
@FeignClient("xc-service-manage-cms") //声明服务名以及调用服务的接口
public interface CmsPageClient extends CmsPageControllerApi {
}