一步步搭建springCloud项目(eureka+swagger+jpa+feign)

初始化数据库表

1、在mysql中创建test数据库并建立user表,以下是数据库脚本

create database test;
use test;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `nick_name` varchar(255) DEFAULT NULL,
  `sex` int(1) DEFAULT NULL,
  `register_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

springcloud项目搭建–构建父工程(1)

1、创建一个maven父工程clouddemo 作为基础工程只保留pom.xml文件(注意packaging一定要选择pom)

  File-->new-->projetc-->maven project

在这里插入图片描述

2、配置 pom.xml

<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>com.zdb</groupId>
	<artifactId>clouddemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	<description>my first springcloud project</description>
  
  
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	<!-- 继承1.5.9RELEASE版本的boot -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath>../pom.xml</relativePath> <!-- lookup parent from repository -->
	</parent>
	<dependencyManagement>
		<!-- SpringCloud依赖,一定要放到dependencyManagement中,起到管理版本的作用即可 -->
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Edgware.SR3</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<!-- 子工程将继承以下依赖 -->
	<dependencies>
		<!-- web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 热部署 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<!-- lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>
</project>

(springboot与springcloud版本对应关系可参考 https://www.cnblogs.com/zhuwenjoyce/p/10261079.html>)

springcloud项目搭建–整合Eureka (2)

1、新建clouddemo-eureka子模块

右击clouddemo工程–>new -->project–>Maven Module

1.1、配置pom.xml文件

<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>
	<parent>
		<groupId>com.zdb</groupId>
		<artifactId>clouddemo</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>clouddemo-eureka</artifactId>
	<packaging>jar</packaging>
	<dependencies>
	<!-- eureka-server 服务端-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</dependency>
	</dependencies>
</project>

1.2、创建ClouddemoEurekaApplication启动类

package com.zdb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer // 开启Eureka服务
public class ClouddemoEurekaApplication {
	public static void main(String[] args) {
		SpringApplication.run(ClouddemoEurekaApplication.class, args);
	}
}

1.3、编写配置文件application.yml

spring:
  profiles:
    active: dev

1.4、编写配置文件application-dev.yml

server:
  port: 10010 # 端口
spring:
  application:
    name: clouddemo-eureka-server # 应用名称,会在Eureka中显示
eureka:
  client:
    register-with-eureka: false # 是否注册自己的信息到EurekaServer,默认是true
    fetch-registry: false # 是否拉取其它服务的信息,默认是true
    service-url: # EurekaServer的地址,现在是自己的地址,如果是集群,需要加上其它Server的地址。
      defaultZone: http://127.0.0.1:${server.port}/eureka
#安全停止服务
endpoints:
  shutdown:
    enabled: true
    sensitive: false

1.5、测试 http://localhost:10010/ 暂无任何服务注册

在这里插入图片描述

2、创建clouddemo-cli子模块注册到eureka服务

右击clouddemo工程–>new -->project–>Maven Module

2.1、pom.xml配置

<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>
	<parent>
		<groupId>com.zdb</groupId>
		<artifactId>clouddemo</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>clouddemo-cli</artifactId>
	<description>clouddemo-client</description>
	<dependencies>
	    <!-- Eureka客户端 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.20</version>
		</dependency>
		<dependency>
			<groupId>tk.mybatis</groupId>
			<artifactId>mapper-spring-boot-starter</artifactId>
			<version>2.0.2</version>
		</dependency>
		<!-- 这里先添加feign的依赖,为整合feign做准备 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
	</dependencies>
</project>

2.2、新建启动类ClouddemoCliApplication

package com.zdb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableEurekaClient // 注册到eureka服务
public class ClouddemoCliApplication {
	public static void main(String[] args) {
		SpringApplication.run(ClouddemoCliApplication.class, args);
	}
}

2.3、控制器类 HelloApi

package com.zdb.api;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
public class HelloApi {
	@GetMapping("index")
	public Object index() {
		return "clouddemo-cli";
	}

}

2.4、配置文件application.yml

spring:
  profiles:
    active: dev

2.5、配置文件application-dev.yml

server:
  port: 10011

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  application:
    name: clouddemo-cli
    
eureka:
  client:
    service-url: # EurekaServer地址
      defaultZone: http://127.0.0.1:10010/eureka
  instance:
    prefer-ip-address: true # 当调用getHostname获取实例的hostname时,返回ip而不是host名称
    ip-address: 127.0.0.1 # 指定自己的ip信息,不指定的话会自己寻找

2.6、配置文件application-prod.yml

server:
  port: 10011

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  application:
    name: clouddemo-cli
    
eureka:
  client:
    service-url: # EurekaServer地址
      defaultZone: http://127.0.0.1:10010/eureka
  instance:
    prefer-ip-address: true # 当调用getHostname获取实例的hostname时,返回ip而不是host名称
    ip-address: 127.0.0.1 # 指定自己的ip信息,不指定的话会自己寻找

3、运行ClouddemoCliApplication,浏览器访问 http://localhost:10011/hello/index

在这里插入图片描述

4、刷新 http://localhost:10010/, 服务clouddemo-cli成功注册

在这里插入图片描述

springcloud项目搭建–整合swagger(3)

1、在父工程clouddemo的pom.xml中添加添加swagger2相关依赖

<!-- swagger2 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.5.0</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.5.0</version>
		</dependency>

完整pom

<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>com.zdb</groupId>
	<artifactId>clouddemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	<description>my first springcloud project</description>
	<modules>
		<module>clouddemo-cli</module>
	</modules>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	<!-- 继承1.5.9RELEASE版本的boot -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath>../pom.xml</relativePath> <!-- lookup parent from repository -->
	</parent>
	<dependencyManagement>
		<!-- SpringCloud依赖,一定要放到dependencyManagement中,起到管理版本的作用即可 -->
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Edgware.SR3</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<!-- 子工程将继承以下依赖 -->
	<dependencies>
		<!-- web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 热部署 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<!-- lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- swagger2 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.5.0</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.5.0</version>
		</dependency>
	</dependencies>


	<build>
		<plugins>
			<!-- springboot打包相关插件 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

2、在子模块clouddemo-cli中新建配置类SwaggerConfig

package com.zdb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
				.select().apis(RequestHandlerSelectors.basePackage("com")) // 扫描com包
				.paths(PathSelectors.any()).build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("ZDB API Doc")
				.description("This is a restful api document of Zdb.")
				.version("1.0").build();
	}
}

3、修改子模块clouddemo-cli的HelloApi

package com.zdb.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
@Api(tags = "Hello模块")
public class HelloApi {
	@GetMapping("index")
	@ApiOperation(value = "swagger测试")
	@ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "name", dataType = "String", required = false, value = "测试参数", defaultValue = "swwager") })
	public Object index(String name) {
		return "clouddemo-cli  " + name;
	}

}

4、浏览器访问 http://localhost:10010/swagger-ui.html

在这里插入图片描述

测试结果

在这里插入图片描述

springcloud项目搭建–整合JPA(3)

1、新建子工程 clouddemo-bean为整合jpa做准备

1.1、引入jpa相关依赖

<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>
	<parent>
		<groupId>com.zdb</groupId>
		<artifactId>clouddemo</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>clouddemo-bean</artifactId>
	<dependencies>
		<!-- jpa-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
	</dependencies>
</project>

1.2、创建User.java

package com.zdb.bean;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

import org.hibernate.annotations.GenericGenerator;

@Data
@Entity
@Table(name = "user")
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer id;
	private String username;
	private String password;
	private int sex;
	@Column(name = "nick_name")
	private String nickName;
	@Column(name = "register_date")
	private Date registerDate;

}

2、新建子工程 clouddemo-jpa

2.1、pom.xml文件配置

<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>
	<parent>
		<groupId>com.zdb</groupId>
		<artifactId>clouddemo</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>clouddemo-jpa</artifactId>
	<packaging>jar</packaging>
	<dependencies>
	<!-- 引入clouddemo-bean 子模块-->
		<dependency>
			<groupId>com.zdb</groupId>
			<artifactId>clouddemo-bean</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.20</version>
		</dependency>
	</dependencies>
</project>

2.2、创建ClouddemoJpaApplication启动类

package com.zdb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient // 注册到eureka服务
public class ClouddemoJpaApplication {
	public static void main(String[] args) {
		SpringApplication.run(ClouddemoJpaApplication.class, args);
	}
}

2.3、新建UserRepository接口

package com.zdb.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.zdb.bean.User;

public interface UserRepository extends JpaRepository<User, Integer>{

}

2.4、 新建UserApi控制器类

package com.zdb.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zdb.bean.User;
import com.zdb.repository.UserRepository;

@RestController
@RequestMapping("user")
public class UserApi {
	@Autowired
	private UserRepository userRepository;

	@GetMapping("fingUserById/{id}")
	public User fingUserById(@PathVariable Integer id) {
		return userRepository.findOne(id);
	}

}

2.5、配置application.yml文件

spring:
  profiles:
    active: dev

2.6、配置application-dev.yml文件

server:
  port: 10012
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  application:
    name: clouddemo-jpa-a   
  jpa:
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    show-sql: true
    properties:
      hibernate:
        format_sql: true
eureka:
  client:
    service-url: # EurekaServer地址
      defaultZone: http://127.0.0.1:10010/eureka
  instance:
    prefer-ip-address: true # 当调用getHostname获取实例的hostname时,返回ip而不是host名称
    ip-address: 127.0.0.1 # 指定自己的ip信息,不指定的话会自己寻找
  main:
    allow-bean-definition-overriding: true #当遇到同样名字的时候,是否允许覆盖注册

3、浏览器访问 http://localhost:10012/user/fingUserById/1

在这里插入图片描述

springcloud项目搭建–整合feign(4)

4.1、在子模块clouddemo-cli引入clouddemo-bean与feign相关依赖

<dependency>
  <groupId>com.zdb</groupId>
  <artifactId>clouddemo-bean</artifactId>
  <version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

4.2、在子模块clouddemo-cli中新建FeignClients接口

package com.zdb.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.zdb.bean.User;


@FeignClient("clouddemo-jpa-a")
public interface FeignClients {
	
	@GetMapping("user/fingUserById/{id}")
	public User findUserByid(@PathVariable("id") Integer id);
}

4.3、修改子模块clouddemo-cli的启动类

package com.zdb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient // 注册到eureka服务
@EnableFeignClients // 注册为feign客户端
public class ClouddemoCliApplication {
	public static void main(String[] args) {
		SpringApplication.run(ClouddemoCliApplication.class, args);
	}
}

4.4、新建UserAip、UserService、FeignClients

package com.zdb.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.sym.Name;
import com.zdb.bean.User;
import com.zdb.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "用户模块", tags = "用户模块")
@RestController
@RequestMapping("user")
public class UserApi {
	@Autowired
	private UserService UserService;

	@GetMapping("/findUserById/{id}")
	@ApiOperation("查询用户")
	public User findUserById(@PathVariable Integer id) {
		return UserService.findOneUser(id);
	}

}


package com.zdb.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zdb.bean.User;
import com.zdb.feign.FeignClients;
@Service
public class UserService {
	@Autowired
	private FeignClients feignClients;

	public User findOneUser(Integer id) {
		return feignClients.findUserByid(id);

	}
}


package com.zdb.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.zdb.bean.User;


@FeignClient("clouddemo-jpa-a")
public interface FeignClients {
	
	@GetMapping("user/fingUserById/{id}")
	public User findUserByid(@PathVariable("id") Integer id);
}

5、swageer测试,也可以直接浏览器访问 http://localhost:10011/user/findUserById/1

在这里插入图片描述

源码地址: https://gitee.com/zcat1024/clouddemo.git
欢迎start。

找呀找呀找工作,微服务啊微服务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值