SpringBoot整合SpringCloud
? 注册中心
服务消费者
服务提供者
2、注册中心配置
在application.yml配置
server:
port: 8761
eureka:
instance:
hostname: eureka-server #eureka实例的主机名
client:
register-with-eureka: false #不把自己注册到eureka上
fetch-registry: false #不从eureka上来获取服务的注册信息
service-url: #服务注册中心的地址
defaultZone: http://localhost:8761/eureka/
主程序使用注解
@EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
3、服务提供者配置
然后把提供者注册到注册中心(application.yml)
server:
port: 8001 #提供者的端口
spring:
application:
name: provider-ticket
eureka:
instance:
prefer-ip-address: true #注册服务时使用服务的ip地址
client:
service-url: #服务注册中心的地址
defaultZone: http://localhost:8761/eureka/
为了注册多个提供者,把第一个提供者8001先打包
然后修改端口号8002继续打包放到同一个文件夹
然后cmd进入到jar包的位置执行命令(出错的话,把注册中心的端口号改为其他,不使用默认)
就可以注册两个提供者
4、服务消费者配置
spring:
application:
name: consumer-user
server:
port: 8200
eureka:
instance:
prefer-ip-address: true #注册服务时使用服务的ip地址
client:
service-url: #服务注册中心的地址
defaultZone: http://localhost:8762/eureka/
主程序使用注解@EnableDiscoveryClient开启服务发现功能
@EnableDiscoveryClient//开启服务发现功能
@SpringBootApplication
public class ConsumerUserApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerUserApplication.class, args);
}
//调用服务
@LoadBalanced//启用负载均衡机制
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
请求层
@RestController
public class UserController {
@Autowired
RestTemplate template;
@GetMapping("/buy")
public String buyTicket(String name){
/**
* 获取票的名字
* 1.PROVIDER-TICKET:服务名
* 2、ticket:地址
* 3、String.class:获取的内容转为string
*/
String s = template.getForObject("http://PROVIDER-TICKET/ticket", String.class);
return name+"购买了"+s;
}
}
访问:http://192.168.56.1:8002/buy
发buy请求会来到RestTemplates请求远程的http://PROVIDER-TICKET/ticket来获取买票的内容,也就是提供者的Controller的方法
负载均衡效果:
第一次访问:8001提供者
第二次:访问8002提供者
第三次:8001
..........