开源项目spring-boot-example

开源项目spring-boot-example

  • github地址:https://github.com/ityouknow/spring-boot-examples
  • 作者:纯洁的微笑
  • 作者专栏:http://www.ityouknow.com/springboot/2016/01/06/spring-boot-quick-start.html

不用记录,作者的文档太好了,没必要摘抄,直接阅读作者的文档即可,关键是后期的具体实现

一、常用依赖



    org.springframework.boot
    spring-boot-starter-web




    org.projectlombok
    lombok




    org.springframework.boot
    spring-boot-devtools
    runtime
    true






    org.webjars
    bootstrap
    4.4.1



    org.webjars
    jquery
    3.4.1




    org.webjars
    webjars-locator
    0.36




    org.apache.commons
    commons-lang3

二、各种配置

1. mysql


    mysql
    mysql-connector-java
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/web-test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

2. jpa



    org.springframework.boot
    spring-boot-starter-data-jpa
spring:
  jpa:
    properties:
      hibernate:
        hbm2ddl.auto: update
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true

3. thymeleaf


    org.springframework.boot
    spring-boot-starter-thymeleaf
spring:
  thymeleaf:
    cache: false
    check-template: true
    check-template-location: true
    servlet.content-type: text/html
    encoding: utf-8
    mode: HTML
    prefix: classpath:/templates/
    suffix: .html

4. spring-boot log配置

logging:
  file:
    path: /user/local/log
  level:
    com.example.demo: INFO
    org.springframework: DEBUG
    org.hibernate: Error
    org.springframework.boot.autoconfigure: ERROR    # 当出现error时显示报告

5. springboot-redis配置



	org.springframework.boot
	spring-boot-starter-data-redis



	org.apache.commons
	commons-pool2
  • 使用jedis:Jedis在实现上是直接连接的redis server,如果在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接
  • 使用Lettuce:Lettuce的连接是基于Netty的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,应为StatefulRedisConnection是线程安全的,所以一个连接实例
spring:
  redis:
    database: 0     # redis索引默认为0
    host: localhost
    port: 6379
    password:       # 默认为空
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        max-wait: -1ms
        min-idle: 0
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
        @Bean
        @ConditionalOnMissingBean(name = "redisTemplate")
        public RedisTemplate redisTemplate(
                        RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
                RedisTemplate template = new RedisTemplate<>();
                template.setConnectionFactory(redisConnectionFactory);
                return template;
        }
        @Bean
        @ConditionalOnMissingBean
        public StringRedisTemplate stringRedisTemplate(
                        RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
                StringRedisTemplate template = new StringRedisTemplate();
                template.setConnectionFactory(redisConnectionFactory);
                return template;
        }
}

  • 其中 StringRedisTemplate 是 RedisTemplate 的子类,两个的方法基本一致,不同之处主要体现在操作的数据类型不同
  • RedisTemplate 中的两个泛型都是 Object ,意味者存储的 key 和 value 都可以是一个对象
  • StringRedisTemplate 的 两个泛型都是 String ,意味者 StringRedisTemplate 的 key 和 value 都只能是字符串
  • 共有方法,例如:.opsForValue().set()        .opsForValue.get()

Redis 数据类型

  • String
  • Hash
  • List
  • Set
  • Zset

特别注意:void set(K key, V value, long timeout, TimeUnit unit);   有失效时间一说

 6. Redis-Session


	org.springframework.session
	spring-session-data-redis
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class SessionConfig {
}

7. mybatis


	org.mybatis.spring.boot
	mybatis-spring-boot-starter
	2.1.1

#{}与${} 

// This example creates a prepared statement, something like select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);

// This example creates n inlined statement, something like select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);

 

两种方式:   (指定别名:

mybatis:
  type-aliases-package: model

注解版与配置版

1) 注解版

例如:

@Select("select * from user")
@Results({
        @Result(property = "email",column = "email"),
        @Result(property = "username",column = "username"),
        @Result(property = "pwd",column = "pwd")
})
List getAll();

2) 配置版

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

mybatis-config.xml


	
		
		
		
		
		
		
	

 UserMapper.xml


    
        
        
        
        
    
    
    
        id, email, username, pwd
    

    

    

    
       INSERT INTO 
       		user
       		(email,username,pwd) 
       	VALUES
       		(#{email}, #{username}, #{pwd})
    
    
    
       UPDATE 
       		users 
       SET 
       	email= #{email},
       	username= #{username},
       	pwd= #{pwd},
       WHERE 
       		id = #{id}
    
    
    
       DELETE FROM
       		 user
       WHERE 
       		 id =#{id}
    

mybatis多数据源:连接两个数据库

其中配置关键: @Primary指定主数据源

  • DataSourceProperties
  • DataSource
  • SqlSessionFactory
  • DataSourceTransactionManager
  • SqlSessionTemplate
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.test1",sqlSessionTemplateRef = "ds1SqlSessionTemplateRef")
public class MybatisDS1Config {

    // 主数据源配置 ds1数据源
    @Primary
    @Bean(name = "ds1DataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSourceProperties ds1DataSourceProperties() {
        return new DataSourceProperties();
    }

    // 主数据源 ds1数据源
    @Primary
    @Bean(name = "ds1DataSource")
    public DataSource ds1DataSource(@Qualifier("ds1DataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    // 主数据源 ds1数据源
    @Primary
    @Bean("ds1SqlSessionFactory")
    public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("ds1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:com/example/demo/mapper/**/*.xml"));
        return sqlSessionFactory.getObject();
    }

    @Primary
    @Bean(name = "ds1TransactionManager")
    public DataSourceTransactionManager ds1TransactionManager(@Qualifier("ds1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "ds1SqlSessionTemplate")
    public SqlSessionTemplate ds1SqlSessionTemplate(@Qualifier("ds1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

8. RabbitMQ

win10安装:Erlang与RabbitMQ安装时版本需要对应

了解:

  • RabbitMQ:消息队列,实现应用程序的异步与解耦,同时起到消息缓冲和消息分发
  • 生产者与消费者
  • AMQP:Advanced Message Queuing Protocol  高级消息队列协议
  • 发消息者、队列、收消息者 

   开源项目spring-boot-example_第1张图片

  • 虚拟主机:一个虚拟主机持有一组交换机、队列和绑定,每一个 RabbitMQ 服务器都有一个默认的虚拟主机“/”
  • 交换机:功能主要时接收消息并且转发到绑定的队列,不做存储,如果没有 Queue bind 到 Exchange 的话,它会直接丢弃掉 Producer 发送过来的消息
  • 绑定:也就是交换机需要和队列相绑定
  • 交换机的类型:Direc类型行为是”先匹配, 再投送”. 即在绑定时设定一个 routing_key, 消息的routing_key 匹配时, 才会被交换器投送到绑定的队列中去;Topic按照规则转发消息;Headers设置 header attribute 参数类型的交换机;Fanout转发消息到所有绑定队列

依赖:


   org.springframework.boot
   spring-boot-starter-amqp
spring:
  application.name: Spring-boot-rabbitmq
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest

9. 定时任务:SchedulerTask


    org.springframework.boot
    spring-boot-starter

 

cron="*/6 * * * * ?"   ==============     fixedRate = 6000 每隔6s打印

10. 邮件服务


	 
	    org.springframework.boot
	    spring-boot-starter-mail
	 
spring:
  mail:
    host: smtp.qq.com
    username: [email protected]
    password: ydciuraeoxbrbadj
    protocol: smtp
    properties:
      mail:
        smtp:
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory
            port: 465
          auth: true
          starttls:
            enable: true
            required: true

ps:邮件的发送者----mailSender.setFrom("发送者邮箱")

11. mongodb   默认没有密码


	org.springframework.boot
	spring-boot-starter-data-mongodb
	2.2.5.RELEASE
spring:
  data:
    mongodb:
      uri: mongodb

使用时要先创建集合(数据库)

12. shiro

摘抄自"纯洁的微笑的springboot笔记" 

shiro功能:  较spring security更加简洁

  • 验证用户身份
  • 用户访问权限控制
  • 在非 Web 或 EJB 容器的环境下可以任意使用 Session API
  • 可以响应认证、访问控制,或者 Session 生命周期中发生的事件
  • 可将一个或以上用户安全数据源数据组合成一个复合的用户 “view”(视图)
  • 支持单点登录(SSO)功能
  • 支持提供“Remember Me”服务,获取用户关联信息而无需登录

开源项目spring-boot-example_第2张图片

shiro架构主要理念:

开源项目spring-boot-example_第3张图片

13. upload

spring:
  servlet:
    multipart:

14. FastDFS  文件分布式文件系统

1) win10 开启tracker服务

docker run -dti --network=host --name tracker -v /var/fdfs/tracker:/var/fdfs delron/fastdfs tracker

2) storage服务

 docker run -dti --network=host --name storage -e TRACKER_SERVER=192.168.0.104:22122 -v /var/fdfs/storage:/var/fdfs delron/fastdfs storage

14. actuator


    org.springframework.boot
    spring-boot-starter-actuator
info:
  app:
    name: spring-boot-actuator
    version: 1.0.0
    test: test
management:
  endpoints:
    web:
      exposure:
        include: "*"
      base-path: /actuator
  endpoint:
    health:
      show-details: always
    shutdown:
      enabled: true

localhost:8080/actuator/info

输出:

{"app":{"name":"spring-boot-actuator","version":"1.0.0","test":"test"}}

15. admin

server端与client端

server端:


	de.codecentric
	spring-boot-admin-starter-server
	2.2.1
server:
  port: 8000

localhost:8000/   启动server

client端:


	de.codecentric
	spring-boot-admin-starter-client
	2.2.1
spring:
  application:
    name: Admin Client
  boot:
    admin:
      client:
        url: http://localhost:8000

management:
  endpoints:
    web:
      exposure:
        include: "*"
server:
  port: 8081

server会监管client

16. docker-nginx-mysql

nginx win10:https://blog.csdn.net/u010417597/article/details/85316714    使用cmd(获取管理员权限)

 

 

 

三、常用工具类

1. MD5Util

public class MD5Util {
    public static String encrypt(String dataStr) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(dataStr.getBytes("UTF8"));
            byte s[] = m.digest();
            String result = "";
            for (int i = 0; i < s.length; i++) {
                result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00)
                        .substring(6);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}

2. userID加密类:Des3EncryptionUtil

3. Base64编码类: Base64

4. 资源过滤配置类:SecurityConfig

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(前后端分离开源项目系列)