基于zookeeper实现springcloud微服务(服务提供者和服务消费者)
本次学习了zookeeper的微服务构建
zookeeper是阿帕奇开源的一种技术,可以作为微服务主机,注册中心等。zookeeper与Eureka的区别在于zookeeper没有保护模式。即当在心跳检测时间过去之后检测不到之前注册的服务的心跳时,其就会毫不留情的将这个服务干掉而不是像Eureka那样过一段时间再干掉没有心跳的服务。由此zookeeper表现出高可用的特征
- 先创建微服务提供者cloud_provider_zk_payment_8004
项目结构
1.pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud2020</artifactId>
<groupId>org.he.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud_provider_zk_payment_8004</artifactId>
<dependencies>
<!-- <dependency>-->
<!-- <groupId>com.atguigu.springcloud</groupId>-->
<!-- <artifactId>cloud-api-commons</artifactId>-->
<!-- <version>${project.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.he.springcloud</groupId>
<artifactId>common_util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zookeeper-discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.application.yml
#次服务注册到zookeeper服务器的端口,也是该应用的服务端口
server:
port: 8004
#服务别名注,册到zookeeper的名称
spring:
application:
name: zk-provider-payment
cloud:
zookeeper:
connect-string: 127.0.0.1:2181
#配置数据源
datasource:
url: jdbc:mysql://localhost:3306/spring?serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
#配置mybatis的mapper配置文件及别名扫描
mybatis:
mapper-locations: classpath:/mappers/*.xml
type-aliases-package: org.he.springcloud.entity
configuration:
#这个配置可以打印sql和结果的
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
log4j配置
#控制日志级别,在哪里输出Output pattern : date [thread] priority category - message FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7
log4j.rootLogger=info,ServerDailyRollingFile,stdout
log4j.logger.weblog=INFO, weblog
log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.ServerDailyRollingFile.File=/Users/xiaocai/IdeaProjects/wmsMobile.log
log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p [%c] - %m%n
log4j.appender.ServerDailyRollingFile.Append=true
#控制台 显示的的方式为控制台普通方式
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#日志输出的格式
log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%c{5}] - %m%n
#打印sql部分
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Connection = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
log4j.logger.java.sql.ResultSet = DEBUG
#配置logger扫描的包路径 这样才会打印sql
log4j.logger.org.he.springcloud.mapper=DEBUG
3.启动类
package org.he.springcloud;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author : hxl
* @Time:2020-10-27
* @Description: zookeeper的服务启动类
*/
@SpringBootApplication
@EnableDiscoveryClient//使用zookeeper或consul作为注册中心时可以使用此朱姐来注册服务
@MapperScan(basePackages = "org.he.springcloud.mapper")
@EnableTransactionManagement//开启事务控制
public class ZkApplication {
public static void main(String[] args) {
SpringApplication.run(ZkApplication.class,args);
System.out.println("zookeeper8004服务已经启动");
}
}
4.dao层
package org.he.springcloud.mapper;
import org.he.springcloud.entity.ZKEntity;
/**
* @author:hxl
* @Time:2020-10-27
* @Description:
*/
public interface ZKMapper {
public void add(ZKEntity zk);
}
5.mapper配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.he.springcloud.mapper.ZKMapper">
<resultMap id="baseMap" type="org.he.springcloud.entity.ZKEntity">
<id property="id" column="id"></id>
<result property="createTime" column="createTime"></result>
<result property="name" column="name"></result>
</resultMap>
<insert id="add" parameterType="org.he.springcloud.entity.ZKEntity">
insert into zklog(id,createTime) values(#{id},#{createTime})
</insert>
</mapper>
6.service
接口\
package org.he.springcloud.service;
import org.he.springcloud.entity.ZKEntity;
/**
* @author:hxl
* @Time:2020-10-27
* @Description:
*/
public interface IZkservice {
public void add(ZKEntity zkEntity);
}
实现类]
package org.he.springcloud.service.impl;
import org.he.springcloud.entity.ZKEntity;
import org.he.springcloud.mapper.ZKMapper;
import org.he.springcloud.service.IZkservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author : hxl
* @Time:2020-10-27
* @Description:
*/
@Service
@Transactional//为service中的方法提供事务控制
public class ZkService implements IZkservice {
@Autowired(required = false)
private ZKMapper mapper;
@Override
public void add(ZKEntity zkEntity) {
mapper.add(zkEntity);
return;
}
}
7.controller
package org.he.springcloud.controller;
import org.he.springcloud.entity.ZKEntity;
import org.he.springcloud.service.IZkservice;
import org.he.springcloud.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.UUID;
/**
* @author : hxl
* @Time:2020-10-27
* @Description:
*/
@RestController
@RequestMapping("/zk")
@CrossOrigin//解决跨域
public class ZkController {
@Autowired
private IZkservice iZkservice;
@GetMapping("/isOk")
public Result isOk(){
ZKEntity zkEntity = new ZKEntity();
//生成uuid同时去除uuid的-
zkEntity.setId(UUID.randomUUID().toString().replaceAll("\\-",""));
zkEntity.setCreateTime(new Date());
zkEntity.setName("zookeeper");
iZkservice.add(zkEntity);
return Result.ok();
}
}
8.实体类
package org.he.springcloud.entity;
import lombok.Data;
import org.aspectj.apache.bcel.classfile.Module;
import java.io.Serializable;
import java.util.Date;
/**
* @author : hxl
* @Time:2020-10-27
* @Description:
*/
@Data
public class ZKEntity implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private Date createTime;
private String name;
}
- 下面创建微服务消费者cloud_consumer_zookeeper_8103
1.pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud2020</artifactId>
<groupId>org.he.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud_consumer_zookeeper_8103</artifactId>
<dependencies>
<dependency>
<groupId>org.he.springcloud</groupId>
<artifactId>common_util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zookeeper-discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.yml
server:
port: 8103
spring:
application:
name: cloud-consumer-zk-8103
#配置连接zookeeper主机的配置
cloud:
zookeeper:
connect-string: 127.0.0.1:2181
3.启动类
package org.he.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author : hxl
* @Time:2020-11-1
* @Description:
*/
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerZkApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerZkApplication.class,args);
System.out.println("ConsumerZkApplication已经启动了");
}
}
4.配置restTemplate
这里贴一下restTemplate是什么,简单来说它是一个发送HTTP请求的工具在微服务中很常用\
RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。
package org.he.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;
/**
* @author : hxl
* @Time:2020-11-1
* @Description: 全局配置类
*/
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced//负载均衡,因为目标微服务不止一个服务构成很有可能是集群微服务提供服务,使用
//负载均衡是的用户只需要使用微服务名号下的任意服务即可,也解决了访问不到微服务的问题
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
5.controller
package org.he.springcloud.controller;
import lombok.extern.slf4j.Slf4j;
import org.he.springcloud.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* @author : hxl
* @Time:2020-11-1
* @Description:
*/
@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {
//目标微服务的服务地址,用户可以访问此访问名下的任意微服务(他们有可能有多个但是提供的服务一样标签暴露一样的名字)
private static final String INVOME_URL="http://zk-provider-payment";
//引入restTemplate
@Resource
private RestTemplate restTemplate;
@GetMapping("isok")
public Result isOk(){
//访问服务提供者zk-provider-payment
Result forObject = restTemplate.getForObject(INVOME_URL + "/zk/isOk", Result.class);
return Result.ok().data("data",forObject);
}
}
- 测试微服务
1.首先启动zookeeper
在下载好的zookeeper中双击/bin/zkServer启动(注意是Windows命令)
出现这种即启动成功
随后启动上面创建的两个微服务
3.然后我们访问服务消费者模拟服务消费者为我们提供了某个功能,然后服务消费者会访问服务提供者,如果执行成功那么为服务成功
1.模拟服务消费者访问以下地址
最终后台显示两者都成功了
返回的结果
服务消费者后台
{NFLoadBalancer:name=zk-provider-payment,current list of Servers=[xxxxx-xxx:8004],Load balancer stats=Zone stats: {unknown=[Zone:unknown; Instance count:1; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
},Server stats: [[Server:xxxx-xxx:8004; Zone:UNKNOWN; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
]}ServerList:org.springframework.cloud.zookeeper.discovery.ZookeeperServerList@318fc5bf
服务提供者后台
表明服务消费者访问zookeeper注册中心的注册的服务提供者成功了并且成功让服务提供者提供了服务
本文地址:https://blog.csdn.net/T1024520/article/details/109440242