springcloud - zookeeper配置
上一个使用了Eureka作为注册中心,基于Spring Cloud实现服务的发布与调用。而在18年7月份,Eureka2.0宣布闭源了
省略zookeeper安装步骤
order模块
application.yml
server: port: 10080 spring: application: name: study-edu-order # 名字随便取一个 profiles: active: dev
application-dev.yml
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/2pc?useSSL=false username: root password: 123 type: com.alibaba.druid.pool.DruidDataSource application: name: study-edu-order cloud: zookeeper: connect-string: study.edu.server:2181 # 本地host文件配置的域名 mybatis: configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
pom文件
<!--微服务相关--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> </dependency>
java部分:
OrderController:
@RestController @RequestMapping("v1/api/order") @Slf4j public class OrderController { @Autowired private DiscoveryClient discoveryClient; @Autowired private OrderService orderService; @PostMapping public CommonResult saveOrder(@RequestBody OrderVO vo) { boolean flag = orderService.saveOrder(vo); log.info("================================>server port is "); if(flag) { return CommonResult.OK(); } else { return CommonResult.NO(); } } }
StockClient接口:
public interface StockClient { CommonResult reduceStock(@RequestBody OrderVO vo); }
StockClientImpl实现接口:
@Service public class StockClientImpl implements StockClient { @Autowired private RestTemplate restTemplate; @Override public CommonResult reduceStock(OrderVO vo) { // 构建调用api服务的路径,stock yml文件取的名字 url为 controller 接口 String uri = String.format("http://study-edu-stock/%s","v1/api/stock"); return restTemplate.postForObject(uri,vo,CommonResult.class); } }
stock模块:
application.yml
server: port: 10090 spring: application: name: study-edu-stock profiles: active: dev
application-dev.yml
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/2pc?useSSL=false username: root password: 123 type: com.alibaba.druid.pool.DruidDataSource cloud: zookeeper: connect-string: study.edu.server:2181 mybatis: configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
pom:
<!--微服务相关--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
StockController:
@RestController @RequestMapping("v1/api/stock") public class StockController { @Autowired private StockService stockService; @PostMapping public CommonResult reduceStock(@RequestBody OrderVO vo) { boolean flag = stockService.reduceStock(vo); if(flag) { return CommonResult.OK(); } else { return CommonResult.NO(); } } }
省略了service ,就是简单的操作数据库来查看负载均衡是否成功
启动服务:可以通过 ZooInspector 插件查看zookeeper节点或者 直接在黑窗口查看,多次调用接口查看是否成功