springcloud工程构建
1.在IDEA中创建空的Maven的project工程: microservice
pom.xml
<?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">
<modelVersion>4.0.0</modelVersion>
<modules>
<module>microservice-api</module>
<module>microservice-provide-dept-8001</module>
<module>microservice-consumer-dept-80</module>
<module>microservice-eureka-7001</module>
<module>microservice-eureka-7002</module>
<module>microservice-eureka-7003</module>
<module>microservice-provide-dept-8002</module>
<module>microservice-provide-dept-8003</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.9.RELEASE</version>
</parent>
<groupId>com.microservice</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<lombok.version>1.18.8</lombok.version>
<guava.version>20.0</guava.version>
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
<druid-druid.version>1.0.9</druid-druid.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Cloud版本-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.9.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--数据库连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<!--德鲁伊连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid-druid.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!--Mybatis启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!--info信息配置-->
<build>
<finalName>microservice</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>
<delimiter>$</delimiter>
</delimiters>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.新建MODULE :microservice-api
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>microservice</artifactId>
<groupId>com.microservice</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>microservice-api</artifactId>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
3.新建microservice-provider-dept-8001 部门微服务提供者Module
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>microservice</artifactId>
<groupId>com.microservice</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>microservice-provide-dept-8001</artifactId>
<dependencies>
<dependency>
<groupId>com.microservice</groupId>
<artifactId>microservice-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jetty -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热部署,修改后立即生效-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!--注册进Eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--监控信息完善-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
application.yml配置
server:
port: 8001
mybatis:
configlocation: classpath:mybatis/mybatis.cfg.xml #Mybatis配置文件所在路径
type-aliases-package: com.microservice.bean #所有bean别名所在包
mapper-locations:
- classpath:mybatis/mapper/**/*.xml #mapper映射文件
spring:
application:
name: microservice-dept #对外暴露的微服务名字
datasource: #数据库连接
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:3306/springcloud?characterEncoding=utf8&useSSL=false
username: root
password: root
#druid连接池配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉监控界面sql无法统计,‘wall’用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
userGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
在resources目录下新建Mybatis 文件夹新建mybatis.cfg.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/><!-- 二级缓存开启 -->
</settings>
</configuration>
数据库脚本:
DROP DATABASE IF EXISTS springcloud;
CREATE DATABASE springcloudCHARACTER SET UTF8;
USE springcloud;
CREATE TABLE dept
(
deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
dname VARCHAR(60),
db_source VARCHAR(60)
);
INSERT INTO dept(dname,db_source) VALUES('开发部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('财务部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市场部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('运维部',DATABASE());
创建DeptDao.java 接口类
package com.microservice.dao;
import com.microservice.bean.Dept;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @create 2019-12-12 14:01
*/
@Mapper
public interface DeptDao {
public boolean addDept(Dept dept);
public Dept findDeptById(Long id);
public List<Dept> findAll();
}
在resources/mybatis目录下新建mapper文件夹后再建DeptMapper.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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="com.microservice.dao.DeptDao">
<!-- id:statement的id 或者叫做sql的id-->
<!-- parameterType:声明输入参数的类型 -->
<!-- resultType:声明输出结果的类型,应该填写pojo的全路径 -->
<!-- #{}:输入参数的占位符,相当于jdbc的? -->
<!--
#{}: 占位符
${}:字符串拼接
-->
<!-- 增加dept -->
<insert id="addDept" parameterType="com.microservice.bean.Dept">
insert into dept values (null,#{dname},DATABASE())
</insert>
<select id="findDeptById" resultType="com.microservice.bean.Dept">
select * from dept where deptno=#{deptno};
</select>
<select id="findAll" resultType="com.microservice.bean.Dept">
select * from dept;
</select>
</mapper>
新建DeptService服务接口
package com.microservice.service;
import com.microservice.bean.Dept;
import java.util.List;
/**
* @create 2019-12-12 14:31
*/
public interface DeptService {
public boolean addDept(Dept dept);
public Dept findDeptById(Long id);
public List<Dept> findAll();
}
DeptServiceImpl实现类
package com.microservice.service.impl;
import com.microservice.bean.Dept;
import com.microservice.dao.DeptDao;
import com.microservice.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @create 2019-12-12 14:32
*/
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptDao dao;
@Override
public boolean addDept(Dept dept) {
return dao.addDept(dept);
}
@Override
public Dept findDeptById(Long id) {
return dao.findDeptById(id);
}
@Override
public List<Dept> findAll() {
return dao.findAll();
}
}
DeptController部门服务提供者RestController
package com.microservice.controller;
import com.microservice.bean.Dept;
import com.microservice.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @create 2019-12-12 14:36
*/
@RestController
@RequestMapping("dept")
public class DeptController {
@Autowired
private DeptService deptService;
// 增加dept
@PostMapping("add")
public boolean addDept(@RequestBody Dept dept){
return deptService.addDept(dept);
}
//根据id查询
@GetMapping("get/{id}")
public Dept findDeptById(@PathVariable("id") Long id){
return deptService.findDeptById(id);
}
// 查询所有
@GetMapping("list")
public List<Dept> findAll(){
return deptService.findAll();
}
DeptProvide8001_APP主启动类
package com.microservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @create 2019-12-12 14:46
*/
@SpringBootApplication
@EnableEurekaClient //本服务开启后会注册进服务中心
@EnableDiscoveryClient//启动服务发现
public class DeptProvide8001_APP {
public static void main(String[] args) {
SpringApplication.run(DeptProvide8001_APP.class,args);
}
}
启动后测试测试:
http://localhost:8001/dept/get/2
http://localhost:8001/dept/list
创建microservice-consumer-dept-80部门微服务消费者Module
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>microservice</artifactId>
<groupId>com.microservice</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>microservice-consumer-dept-80</artifactId>
<description>部门微服务的消费者</description>
<dependencies>
<dependency>
<groupId>com.microservice</groupId>
<artifactId>microservice-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热部署,修改后立即生效-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>
yml
server:
port: 80
创建configBean
RestTemplate提供了多种便捷访问远程Http服务的方法,
是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集
官网地址官网
使用
使用restTemplate访问restful接口非常的简单粗暴无脑。
(url, requestMap, ResponseBean.class)这三个参数分别代表
REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
package com.microservice.cfgbeans;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
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;
/**
* @create 2019-12-12 15:37
*/
@Configuration
public class ConfigBean {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
代码
package com.microservice.controller;
import com.microservice.bean.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* @create 2019-12-12 15:41
*/
@RestController
@RequestMapping("consumer")
public class DeptController_consumer {
private static final String REST_URL_PREFIX="http://MICROSERVICE-DEPT";
@Autowired
private RestTemplate restTemplate;
@RequestMapping("dept/add")
public boolean addDept(Dept dept){
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
}
@RequestMapping("dept/get/{id}")
public Dept findDeptById(@PathVariable("id")Long id){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class);
}
@RequestMapping("dept/list")
public List<Dept> addDept(){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class);
}
启动类Deptconsumer80_APP
package com.microservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
/**
* @create 2019-12-12 15:34
*/
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name="MICROSERVICE-DEPT")
public class Deptconsumer80_APP {
public static void main(String[] args) {
SpringApplication.run(Deptconsumer80_APP.class,args);
}
}
测试
http://localhost/consumer/dept/get/2
http://localhost/consumer/dept/list
http://localhost/consumer/dept/add?dname=AI