支付和消费模块接入Euraka集群
支付模块的设置
更改支付模块的yml
server:
port: 8001
eureka:
client:
#表示是否将自己注册进Eurekaserver默认为true。
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
defaultZone: http://127.0.0.1:7001/eureka,http://localhost:7002/eureka,http://192.168.0.135:7003/eureka
spring:
application:
name: cloud-payment-service
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/my?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.gcl.springcloud.entities
消费模块的设置
更改消费模块的yml
server:
port: 8080
spring:
application:
name: cloud-order-service
eureka:
client:
#表示是否将自己注册进Eurekaserver默认为true。
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
defaultZone: http://127.0.0.1:7001/eureka,http://localhost:7002/eureka,http://192.168.0.135:7003/eureka
更改消费模块的控制层调用(主要是请求的地址更改了,更改为提供服务的微服务应用名)
package com.gcl.springcloud.controller;
import com.gcl.springcloud.entities.CommonResult;
import com.gcl.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
@Slf4j
public class OrderController {
private static final String PAYMENT_URL = "http://cloud-payment-service";
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "/consumer/payment/create")
public CommonResult<Payment> create(Payment payment){
return restTemplate.postForObject( PAYMENT_URL + "/payment/create" , payment , CommonResult.class);
}
@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id ){
return restTemplate.getForObject( PAYMENT_URL + "/payment/get/" + id , CommonResult.class);
}
}
RestTemplate启用@LoadBalanced负载均衡
package com.gcl.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
当前的架构
需要注意的是虽然我们使用的是Eureka的集权架构,但是当前提供服务的支付模块只有一个。还体现不出来@LoadBalance的负载均衡,我们下一篇就实现多个课提供服务的负载均衡案例。
运行截图