Spring Cloud Consul 构建基础服务


说明

简介


  • 首先,这是一个标准的 Spring Boot 项目
  • 其次,它实现基于 ​​Spring Cloud Consul​​的服务注册功能
  • 最后,它通过 Mybatis 实现数据库的访问功能

创建项目

  • 博主使用的 Intellij IDEA 作为开发攻击,创建的项目的目录结构如下所示:

    • Spring Cloud Consul 构建基础服务_Mybatis
    • 它主要包含六部分内容:

      • 依赖信息:pom.xml
      • 配置信息:application.yml
      • 启动类: AwesomeUserServerApplication.java
      • 控制器类:UserController.java
      • Service 层接口类以及它的实现类:UserService.java、UserServiceImpl.java
      • Dao 层接口类以及它对应的 Mapper:UserDao.java、user_mapper.xml


依赖信息


  • 主要引入依赖:

    • spring-cloud-starter-consul-all:注册服务到 Consul
    • mybatis-spring-boot-starter: 支持 Mybatis 服务
    • mysql-connector-java:博主使用 Mysql 作为数据库服务器

  • 完整 pom.xml
  • <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0">​http://maven.apache.org/POM/4.0.0​" xmlns:xsi="www.w3.org/2001/XMLSchema-instance">​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"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>andy.wanna.sing</groupId> <artifactId>awesome-user-server</artifactId> <version>0.0.1-SNAPSHOT</version> <name>awesome-user-server</name> <description>awesome-user-server</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR1</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-all</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
  • 主要配置内容:

    • 服务注册中心(Spring Cloud Consul 配置)
    • 数据源配置
      • 博主的数据库版本是 8.x,mysql-connector-java 的版本也是 8.x,因此,使用新的驱动类:com.mysql.cj.jdbc.Driver
    • mybatis 配置:

      • 配置包路径
      • 配置 mapper 文件的路径

    • 运行的端口号
    • 健康检查暴露的端点

  • application.yml
  • ​spring: application: name: awesome-user-server cloud: consul: host: localhost port: 8500 discovery: enabled: true register: true healthCheckInterval: 10s instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}} config: watch: enabled: true datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/andy_test?serverTimezone=UTC username: Andy password: 123456 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: awesome.user.server server: port: 9401 management: endpoints: web: exposure: include: metrics,env,beans,mappings,health ​

启动类


  • 标准的 Spring Boot 项目启动类
  • package awesome.user.server;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class AwesomeUserServerApplication { public static void main(String[] args) { SpringApplication.run(AwesomeUserServerApplication.class, args); }}

控制器类

  • 提供一个用户接口,

    • 匹配 uri : ​​/api/user/{id}​
    • package awesome.user.server.controller.user;import awesome.user.server.bean.User;import awesome.user.server.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;/** * 用户控制器 * * @author: Andy * @time: 2019/4/16 21:36 * @since */ @RestControllerpublic class UserController { @Autowired private UserService userService; /** * 获取用户信息 * * * @param id 用户ID * @return: {@link ResponseEntity<User> } * @author: Andy * @time: 2019/4/16 22:02 */ @GetMapping("/api/user/{id}") public ResponseEntity<?> getUser(@PathVariable("id") Integer id){ try { ResponseEntity<?> responseEntity = userService.getUser(id); if(responseEntity.getStatusCode() == HttpStatus.OK){ return new ResponseEntity<>(responseEntity.getBody(), HttpStatus.OK); } return new ResponseEntity<>("请求失败!", responseEntity.getStatusCode()); }catch (Exception e){ //todo: do something return new ResponseEntity<>("请求失败!", HttpStatus.INTERNAL_SERVER_ERROR); } }}

Service 层接口类以及它的实现类


  • 接口类
    • package awesome.user.server.service;import awesome.user.server.bean.User;import org.springframework.http.ResponseEntity;public interface UserService { /** * 根据用户 ID 获取用户信息 * * * @param id * @return: {@link ResponseEntity<User> } * @author: Andy * @time: 2019/4/18 11:08 * @since */ ResponseEntity<?> getUser(Integer id);}
  • 接口实现类

    • 在 IDEA 中, ​​private UserDao userDao​​​这一行有报错提示:​​Can not autowire​​​。根据博主检索的资料,这是 IDEA 的BUG,它没有正确识别 ​​@Mapper​​注解。可以通过注解来抑制这个报错,也可以不处理。
    • package awesome.user.server.service.impl;import awesome.user.server.bean.User;import awesome.user.server.dao.UserDao;import awesome.user.server.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Service;/** * 用户服务实现类 * * @author: Andy * @time: 2019/4/18 11:07 * @since */ @Servicepublic class UserServiceImpl implements UserService { @Autowired private UserDao userDao; /** * 根据用户 ID 获取用户信息 * * * @param id * @return: {@link ResponseEntity<User> } * @author: Andy * @time: 2019/4/18 11:08 * @since */ @Override public ResponseEntity<?> getUser(Integer id) { User user = userDao.getUserById(id); if(user != null){ return new ResponseEntity<>(user, HttpStatus.OK); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); }}


Dao 层接口类以及它对应的 Mapper


  • UserDao :
    • package awesome.user.server.dao;import awesome.user.server.bean.User;import org.apache.ibatis.annotations.Mapper;/** * @author: Andy * @time: 2019/4/18 14:22 * @since */ @Mapperpublic interface UserDao { User getUserById(Integer id);}
  • user_mapper.xml:
    • <?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="awesome.user.server.dao.UserDao"> <select id="getUserById" resultMap="userMap"> SELECT id,name FROM user WHERE id = #{id} </select> <resultMap id="userMap" type="awesome.user.server.bean.User"> <id column="id" jdbcType="INTEGER" property="id"/> <id column="name" jdbcType="VARCHAR" property="name"/> </resultMap></mapper>

测试

IP 访问

  • Spring Cloud Consul 构建基础服务_spring_02

根据服务名访问