SpringBoot和SpringCloud搭建(持续更新版)

SpringBoot 快速搭建

前言

Spring Boot,约定大于配置,则么说呢,就是爽就完事了,我想以后搭建不那么麻烦,开袋即食! 但是有的地方需要自己更改!!!有些地方我会注释掉,按需获取!

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.0modelVersion>

    
    <groupId>org.examplegroupId>
    <artifactId>testSpringBootartifactId>
    <version>1.0-SNAPSHOTversion>

    
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-parentartifactId>
        <version>2.0.6.RELEASEversion>
    parent>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        
    dependencies>
project>

启动类

//相当于三个注解
@SpringBootApplication
public class SpringBootStartAppTest {

    public static void main(String[] args) {

        SpringApplication.run(SpringBootStartAppTest.class,args);

    }
}

拓展组件

好用的其他组件移步

SpringCloud

注册中心

nacos

  • Nacos 是阿里巴巴推出来的一个新开源项目,这是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。
  • Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。
  • Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以"服务"为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施

使用很简单,具体移步官网,之后配置文件会标注两种注册中心,用哪个自己决定。

eureka

启动类
@SpringBootApplication
@EnableEurekaServer
public class EurekaStart {
    public static void main(String[] args) {
        SpringApplication.run(EurekaStart.class,args);
    }
}


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.0modelVersion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.6.RELEASEversion>
        <relativePath/> 
    parent>
    
    <groupId>org.examplegroupId>
    <artifactId>eurekaartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
        <spring-cloud.version>Finchley.SR2spring-cloud.version> 
    properties>

    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

application.yml 配置文件
server:
  #设置端口
  port: 10086

spring:
  application:
    #设置应用名称
    name: work-eureka

eureka:
  client:
    service-url:
      #注册地址  注册中心也要像eureka注册
      defaultZone: http://127.0.0.1:${server.port}/eureka/

一般注册中心就提供一个注册中心的服务,其他都不用提供

work-provider 提供方

启动类

@SpringBootApplication
@EnableDiscoveryClient
public class StartPro {
    public static void main(String[] args) {
        SpringApplication.run(StartPro.class, args);
    }
}

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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.6.RELEASEversion>
        <relativePath/> 
    parent>
    
    <groupId>cn.yhgroupId>
    <artifactId>work-providerartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
        <spring-cloud.version>Finchley.SR2spring-cloud.version> 
    properties>

    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>


    <dependencies>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

project>

application.yml 文件


server:
  #定义端口  要不一样  避免冲突
  port: 8081

spring:
  application:
    #微服务的名字
    name: work-provider
  #数据源的配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///day0523work?useSSL=false
    username: root
    password: root

#注册中心的配置  向哪个注册中心进行配置
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka/
## nacos服务地址
#spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

拓展组件

好用的其他组件移步

work-comsumer 消费者

启动类
@SpringCloudApplication
@EnableFeignClients
public class StartCom {
    public static void main(String[] args) {
        SpringApplication.run(StartCom.class, args);
    }
}

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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.6.RELEASEversion>
        <relativePath/> 
    parent>


    <groupId>cn.yhgroupId>
    <artifactId>work-comsumerartifactId>
    <version>1.0-SNAPSHOTversion>

    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>Finchley.SR2version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>


    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-hystrixartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>

    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
application.yml 文件
#调用方端口  避免冲突应不一样
server:
  port: 8080


spring:
  application:
    #消费者的服务名称
    name: work-comsumer

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka/
## nacos服务地址
#spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

拓展组件

好用的其他组件移步
注意远程调用调用传入对象好像只能传入json格式的数据

zuul 网关注册

启动类
@EnableZuulProxy // 开启网关功能
@SpringCloudApplication
public class ZulApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZulApplication.class,args);
    }
}
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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.6.RELEASEversion>
        <relativePath/> 
    parent>

    <groupId>cn.yhgroupId>
    <artifactId>work-api-zuulartifactId>
    <version>1.0-SNAPSHOTversion>

    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>Finchley.SR2version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-zuulartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
    dependencies>
project>
application.yml 文件
server:
  port: 10010

spring:
  application:
    name: api-gateway

eureka:
  client:
    service-url: #eureka服务地址
      defaultZone: http://127.0.0.1:10086/eureka/
zuul:
  routes:
    provider-service: /provider-service/**
    consumer-service: /consumer-service/**
  prefix: /api #添加路由前缀

一些组件的用法和配置

MyBatis Plus

作为一个 MyBatis的增强版,可谓增强到爽,因为在哪个工程中都可能用到这个,所以单独列出来,方便使用

添加依赖



<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>

<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.2.2version>
dependency>

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-boot-starterartifactId>
    <version>3.3.1version>
dependency>

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>mybatis-plus-extensionartifactId>
    <version>3.3.1version>
dependency>

复制添加到你想要添加的工程pom文件种的 dependencies标签中

添加配置文件 application.yml

spring:
  #数据源的配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///day0515work?useSSL=false
    username: root
    password: root

注意添加位置不要给错了

给配置类中添加分页的bean

package cn.yh.work.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * MybatisPlus配置类
 */
@EnableTransactionManagement //事务处理
@Configuration
public class MybatisPlusConfig {
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

赘述

  • 在配置文件添加数据源对应的配置
spring:
  #数据源的配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///day0515work?useSSL=false
    username: root
    password: root
  • 添加mapper

DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        
<mapper namespace="cn.yh.work.mapper.UserMapper">
mapper>
  • 添加mapper对应的类
@Mapper
public interface UserMapper extends BaseMapper<User> {}
  • 添加表对应的实体类
@Data
public class User {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthday;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}
  • service层的改变
public interface UserService extends IService<User> {}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}

总结: 基本上这样在controller中注入已经curd齐全了,像其他的一些功能需要了自己看文档或者百度都可以

Redis && 缓存

一般不会操作其中的数据库,都是通过redis配合spring cache这个组件一起使用,也比较简单,如果需要具体操作redis,可以自行百度RedisTemplate的使用,也很简单

添加依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>

<dependency>
    <groupId>org.apache.commonsgroupId>
    <artifactId>commons-pool2artifactId>
    <version>2.6.0version>
dependency>  

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-cacheartifactId>
dependency>
<dependency>
    <groupId>net.sf.ehcachegroupId>
    <artifactId>ehcacheartifactId>
dependency>

使用方法

添加配置类
@Configuration
@EnableCaching
public class RedisConfig {
    /**
     * 自定义key规则
     * @return
	 */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    /**
     * 设置RedisTemplate规则
     * @param redisConnectionFactory
	 * @return
	 */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //序列化key value
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    /**
     * 设置CacheManager缓存规则
     * @param factory
	 * @return
	 */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(600))
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
            .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .build();
        return cacheManager;
    }
}

2.1 常用缓存标签

2.1.2 缓存 @Cacheable

根据方法对其返回结果进行缓存,下次请求时,如果缓存存在,则直接读取缓存数据返回;如果缓存不存在,则执行方法,并把返回的结果存入缓存中。一般用在查询方法上。

查看源码,属性值如下:

属性/方法名 解释
value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
key 可选属性,可以使用 SpEL 标签自定义缓存的key
2.1.2 缓存 @CachePut

使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。其他方法可以直接从响应的缓存中读取缓存数据,而不需要再去查询数据库。一般用在新增方法上。

查看源码,属性值如下:

属性/方法名 解释
value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
key 可选属性,可以使用 SpEL 标签自定义缓存的key
2.1.3 缓存 @CacheEvict

使用该注解标志的方法,会清空指定的缓存。一般用在更新或者删除方法上

查看源码,属性值如下:

属性/方法名 解释
value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
key 可选属性,可以使用 SpEL 标签自定义缓存的key
allEntries 是否清空所有缓存,默认为 false。如果指定为 true,则方法调用后将立即清空所有的缓存
beforeInvocation 是否在方法执行前就清空,默认为 false。如果指定为 true,则在方法执行前就会清空缓存

赘述

在配置文件添加对应的

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000

MongoDb数据库

添加依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>

赘述

  • 添加repository层
public interface DepartmentRepository extends MongoRepository<Department,String> {}
//在service层注入已经基本有了curd的操作
  • 添加实体类
@Data
@EqualsAndHashCode(callSuper = true)
@Document("Department")
public class Department  {
	private static final long serialVersionUID = 1L;
	@Indexed //普通索引
	private String hoscode;
	@Indexed(unique = true) //唯一索引
	private String depcode;
	private String depname;
	private String intro;
	private String bigcode;
	private String bigname;
}
  • 愉快使用~~

swagger文档注释

引入依赖


<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-boot-starterartifactId>
    
    <exclusions>
        <exclusion>
            <groupId>io.swaggergroupId>
            <artifactId>swagger-annotationsartifactId>
        exclusion>
        <exclusion>
            <groupId>io.swaggergroupId>
            <artifactId>swagger-modelsartifactId>
        exclusion>
    exclusions>
dependency>

<dependency>
    <groupId>com.github.xiaoymingroupId>
    <artifactId>knife4j-spring-boot-starterartifactId>
dependency>

赘述

  • 添加配置类
@Configuration
@EnableOpenApi // 开启Swagger3   可不写
@EnableKnife4j // 开启knife4j增强 可不写
public class Swagger3Config {
    @Bean
    public Docket webApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                //只显示api路径下的页面
                .paths(PathSelectors.regex("/api/.*"))
                .build();
    }
    @Bean
    public Docket adminApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("adminApi")
                .apiInfo(adminApiInfo())
                .select()
                //只显示admin路径下的页面
                .paths(PathSelectors.regex("/admin/.*"))
                .build();
    }
    private ApiInfo webApiInfo(){
        return new ApiInfoBuilder()
                .title("网站-API文档")
                .description("本文档描述了网站微服务接口定义")
                .version("1.0")
                .contact(new Contact("yh", "http://www.yunhe.cn", "[email protected]"))
                .build();
    }
    private ApiInfo adminApiInfo(){
        return new ApiInfoBuilder()
                .title("后台管理系统-API文档")
                .description("本文档描述了后台管理系统微服务接口定义")
                .version("1.0")
                .contact(new Contact("yh", "http://www.yunhe.cn", "[email protected]"))
                .build();
    }
}

你可能感兴趣的:(spring,cloud,spring,boot,eureka)