原生态REST学习环境搭建
1、Rest学习环境搭建:服务提供者
1.1、创建父工程springcloud_demo
以maven的方式创建父工程
父工程为springcloud_demo
- 父工程主要是定义POM文件,将后续各个子模块公用的jar包等统一提取出来,类似一个抽象父类
- 切记Packageing是pom模式
父工程的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>
<groupId>org.example</groupId>
<artifactId>springcloud_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>springcloud-api</module>
<module>springcloud-provider-dept-8001</module>
<module>springcloud-consumer-dept-80</module>
</modules>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<lombok.version>1.16.18</lombok.version>
<swagger.version>2.7.0</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.2.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--springCloud的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--SpringBoot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.4.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--SpringBoot 启动器-->
<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-devtools</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<!--日志测试~-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</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>
</dependency>
</dependencies>
</project>
1.2、搭建子module–springcloud-api
子module的创建方式仍为maven
**备注:**api的模块主要为服务提供实体,无其它作用
创建实体类部门Dept
实体类代码:
package com.hy.springcloud.api.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
/*
@Author: hy
*/
/*
api模块仅提供实体类
*/
@Data//简略构造器、 get set方法等
@NoArgsConstructor //无参构造注解
@Accessors //链式写法
public class Dept implements Serializable { //Dept实体类
private Long deptno;//主键
private String dname;
//微服务,一个服务对应一个数据库,同一信息可能存在不同数据库
private String db_source;
//构造器
public Dept(String dname){
this.dname=dname;
}
/*
链式写法
Dept dept = new Dept()
原始:dept.setDeptNo(11) dept.setDname('技术部') ...
链式:dept.setDeptNo(11).setDname('技术部')
*/
}
1.3、服务提供方搭建
整体结构如下:
1、以maven方式创建springcloud-provider-dept-8001
2、编写pom配置
需要拿到实体类,并以pom方式引入,所以需要在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>springcloud_demo</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-provider-dept-8001</artifactId>
<dependencies>
<!--我们需要拿到实体类,所以要配置api module-->
<dependency>
<groupId>org.example</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
3、配置文件application.yml
server:
port: 8001
#mybatis配置
mybatis:
type-aliases-package: com.hy.springcloud.api.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
#spring配置
spring:
application:
name: springcloud-provider-dept #别名
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/hy_cloud?useUnicode=true&characterEncoding=utf-8
username: root
password: root
4、编写Dao、Service、Controller层
1、Dao层
package com.hy.springcloud.dao;
import com.hy.springcloud.api.pojo.Dept; //从pom.xml导入
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/*
Auhtor: hy
*/
@Mapper
@Repository
public interface DeptDao {
public boolean addDept(Dept dept);
public Dept queryById(Long id);
public List<Dept> queryAll(); //查询所有
public boolean deleteById(Long id);
public boolean updateDept(Dept dept);
}
2、mapper文件xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hy.springcloud.dao.DeptDao">
<insert id="addDept" parameterType="Dept">
insert into dept (dname,db_source)
values (#{dname},DATABASE());
</insert>
<select id="queryById" resultType="Dept" parameterType="Long">
select * from dept where deptno=#{id};
</select>
<select id="queryAll" resultType="Dept">
select * from dept;
</select>
<delete id="deleteById" parameterType="Long">
delete * from dept where deptno=#{id};
</delete>
<update id="updateDept" parameterType="Dept">
update dept set dname=#{dname};
</update>
</mapper>
3、Service层
package com.hy.springcloud.service;
import com.hy.springcloud.api.pojo.Dept;
import java.util.List;
/*
Author: hy
*/
public interface DeptService {
public boolean addDept(Dept dept);
public Dept queryById(Long id);
public List<Dept> queryAll(); //查询所有
public boolean deleteById(Long id);
public boolean updateDept(Dept dept);
}
4、Service接口实现
package com.hy.springcloud.service;
import com.hy.springcloud.api.pojo.Dept;
import com.hy.springcloud.dao.DeptDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.PrivateKey;
import java.util.List;
/*
author: hy
*/
@Service
public class DeptServiceImpl implements DeptService{
@Autowired
private DeptDao deptDao;
@Override
public boolean addDept(Dept dept) {
return deptDao.addDept(dept);
}
@Override
public Dept queryById(Long id) {
return deptDao.queryById(id);
}
@Override
public List<Dept> queryAll() {
return deptDao.queryAll();
}
@Override
public boolean deleteById(Long id) {
return deptDao.deleteById(id);
}
@Override
public boolean updateDept(Dept dept) {
return deptDao.updateDept(dept);
}
}
5、Controller层
package com.hy.springcloud.controller;
import com.hy.springcloud.api.pojo.Dept;
import com.hy.springcloud.service.DeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.PAData;
import javax.xml.ws.http.HTTPBinding;
import java.util.List;
/*
author: hy
*/
@RestController //与前端不交互,使用RestController
@Api(tags = "Dept测试")
public class DeptController {
@Autowired
private DeptService deptService;
@ApiOperation(value = "添加部门")
@PostMapping(path = "/dept/add")
public boolean addDept(Dept dept){
return deptService.addDept(dept);
}
@ApiOperation(value = "查询部门")
@GetMapping(path = "/dept/get/{id}")//RestFul风格
public Dept queryById(@PathVariable("id") Long id){
return deptService.queryById(id);
}
@ApiOperation(value = "查询所有部门")
@GetMapping(path = "/dept/list")
public List<Dept> queryALL(){
return deptService.queryAll();
}
@ApiOperation(value = "删除部门")
@DeleteMapping(path = "/dept/del/{id}")
public boolean deleteById(@PathVariable("id") Long id ){
return deptService.deleteById(id);
}
@ApiOperation(value = "更新部门")
@PutMapping(path = "/dept/update")
public boolean updateDept(Dept dept){
return deptService.updateDept(dept);
}
}
5、创建主启动类
package com.hy.springcloud;
/*
author: hy
*/
//启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DeptProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(DeptProvider_8001.class,args);
}
}
6、启动测试
http://localhost:8001/dept/list
2、Rest学习环境搭建:服务消费者
2.1、搭建消费方子module
仍以maven的方式创建
需要注意的是:消费方只负责消费,所以只有Controller层
整体结构如下:
2.1、配置pom文件与yml文件
**备注:**pom文件依赖仍从父工程引入,只需在 pom文件中引入实体类
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">
<parent>
<artifactId>springcloud_demo</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-consumer-dept-80</artifactId>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>springcloud-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
application.xml文件:
只需配置服务端口号
server:
port: 80
2.3、ConfigBean与Controller层
1、ConfigBean
- RestTemplate 提供多种便捷访问远程http服务的方法,简单的Restful服务模板~
- RestTemplate供我们直接调用!需要自行注册到spring中!
package com.hy.springcloud.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ConfigBean { //Configuration --spring applicationContext.xml
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
2、Controller层
package com.hy.springcloud.controller;
import com.hy.springcloud.api.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/*
消费者与服务提供者实现了完全解耦
*/
@RestController
public class DeptConsumerController {
//理解:消费者不应该有service层
//RestTemplate ....供我们直接调用!注册到spring中
/**
* 理解:消费者,不应该有service层~
* RestTemplate .... 供我们直接调用就可以了! 注册到Spring中
* (地址:url, 实体:Map ,Class<T> responseType)
* <p>
* 提供多种便捷访问远程http服务的方法,简单的Restful服务模板~
*/
@Autowired
private RestTemplate restTemplate;
/**
* 服务提供方地址前缀
* <p>
* Ribbon:我们这里的地址,应该是一个变量,通过服务名来访问
*/
private static final String REST_URL_PREFIX = "http://localhost:8001";
//private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
/**
* 消费方添加部门信息
* @param dept
* @return
*/
@RequestMapping("/consumer/dept/add")
public boolean add(Dept dept) {
// postForObject(服务提供方地址(接口),参数实体,返回类型.class)
return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);
}
/**
* 消费方根据id查询部门信息
* @param id
* @return
*/
@RequestMapping("/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id) {
// getForObject(服务提供方地址(接口),返回类型.class)
return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);
}
/**
* 消费方查询部门信息列表
* @return
*/
@RequestMapping("/consumer/dept/list")
public List<Dept> list() {
return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
}
}
2.4、创建主启动类
DeptConsumer_80
**备注:**需要排除datasource的自动注解,否则可能启动报错:配置数据源失败
package com.hy.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //排除datasource的自动注解 否则会报错:配置数据源失败
public class DeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(DeptConsumer_80.class,args);
}
}
2.5、启动测试
http://localhost/consumer/dept/list
3、总结说明
以上就是原生态的Rest服务搭建详细流程,若仍有问题或需要sql文件,评论或私信!!!