Hexo Blog

fsh的博客


  • 首页

  • 归档

Spring-Boot 集成SpringSecurit

发表于 2018-12-26 更新于 2019-02-14

Spring securit

简介

Spring securit是基于Spring的安全框架,他的主要功能是认证和鉴权,主要原理是通关一系列的拦截器和过滤器来实现

核心组件

1、WebSecurityConfig===》WebSecurityConfigurerAdapter(主要配置文件,代替原先XML文件)
2、MyAuthenticationProvider==》AuthenticationProvider(初始化用户)
3、CustomUserDetailsService==》UserDetailsService(MyAuthenticationProvider需要调用)
4、mySecurityFilter==》AbstractSecurityInterceptor 、Filter(自定义的过滤器)
5、FilterSourceMetadataSource==》FilterInvocationSecurityMetadataSource(加载需要过滤的数据)
6、MyAccessDecisionManager ==》AccessDecisionManager(过滤器调用,验证用户是否有权限访问资源)

核心功能

原理

通过拦截器认证(AuthenticationProvider)用户信息,通过过滤器鉴别用户是否有权限(AccessDecisionManager)

WebSecurityConfigurerAdapter

Spring-Boot-MyBatis-Plus插件

发表于 2018-12-11 更新于 2019-01-29

快速开始

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

添加依赖

1
2
3
4
5
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7.1</version>
</dependency>

配置

在 application.yml 配置文件中添加 H2 数据库的相关配置:

1
2
3
4
5
6
7
8
9
# DataSource Config
spring:
datasource:
driver-class-name: org.h2.Driver
schema: classpath:db/schema-h2.sql
data: classpath:db/data-h2.sql
url: jdbc:h2:mem:test
username: root
password: test

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {

public static void main(String[] args) {
SpringApplication.run(QuickStartApplication.class, args);
}

}

实体类

编写实体类 User.java(此处使用了 Lombok 简化代码和TableName来注明表名称)

1
2
3
4
5
6
7
8
@TableName("t_user")
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}

编写Mapper类 UserMapper.java 并继承 BaseMapper UserMapper接口中可以直接写查询sql语句
也可以使用继承来的查询方法

1
2
3
4
public interface UserMapper extends BaseMapper<User> {
@Select("select * from t_User where username = #{username}")
UserDO getByUsername(String username);
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {

@Autowired
private UserMapper userMapper;

@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}

}

小结

通过以上几个简单的步骤,我们就实现了 User 表的 CRUD 功能,甚至连 XML 文件都不用编写!
从以上步骤中,我们可以看到集成MyBatis-Plus非常的简单,只需要引入 starter 工程,并配置 mapper 扫描路径即可。
同时MyBatis-Plus也提供分页查询以及自定义扩展的接口,但是由于是开源的框架,作者好像完全没有考虑到兼容性,导致后面的升级十分困难。

Spring-Boot 权限控制

发表于 2018-12-07 更新于 2019-01-29

实现权限控制

Spring-Boot 权限控制 一般基于两种方式来实现 一种是url 另一种是基于code也就是注解来实现。

SpringSecurity权限框架

用户登陆,会被AuthenticationProcessingFilter拦截(即认证管理),调用AuthenticationManager的实现,而且AuthenticationManager会调用ProviderManager来获取用户验证信息(不同的Provider调用的服务不同,因为这些信息可以是在数据库上,可以是在LDAP服务器上,可以是xml配置文件上等),
如果验证通过后会将用户的权限信息封装一个User放到spring的全局缓存SecurityContextHolder中,以备后面访问资源时使用。

访问资源(即授权管理),访问url时,会通过AbstractSecurityInterceptor拦截器拦截,
其中会调用FilterInvocationSecurityMetadataSource的方法来获取被拦截url所需的全部权限,
在调用授权管理器AccessDecisionManager,这个授权管理器会通过spring的全局缓存SecurityContextHolder获取用户的权限信息,还会获取被拦截的url和被拦截url所需的全部权限,【然后根据所配的策略】(有:一票决定,一票否定,少数服从多数等),如果权限足够,则返回,权限不够则报错并调用权限不足页面。

Interceptor拦截器

通过Spring Security 配置一个springSecurityFilterChain的Servlet过滤器,来对我们应用中所有的安全相关的事项(保护应用的所有url,验证用户名密码,表单重定向等)负责。

Spring Security原理,使用众多过滤器

UriInvocationSecurityMetadataSourceService

将用户当前角色读取到session中
请求时,通过请求的url查询对应的功能点找到相关连的角色
对比当前用户的角色是否在存在于关联角色中,有则放行,没有则告知没有权限
扩展添加权限注解,有注解的跳过权限验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.us.example.config;

import com.us.example.service.CustomUserService;
import com.us.example.service.MyFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
* Created by yangyibo on 17/1/18.
*/


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private MyFilterSecurityInterceptor myFilterSecurityInterceptor;

@Bean
UserDetailsService customUserService(){ //注册UserDetailsService 的bean
return new CustomUserService();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()); //user Details Service验证
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated() //任何请求,登录后可以访问
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.and()
.logout().permitAll(); //注销行为任意访问
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
}
}

注解
@Autowired默认是根据类型进行注入的,因此如果有多个类型一样的Bean候选者,则需要限定其中一个候选者,否则将抛出异常

@Qualifier限定描述符除了能根据名字进行注入,更能进行更细粒度的控制如何选择候选者,具体使用方式如下:

读取和写入分开
系统加载时根据子系统区分缓存用户角色功能

权限扩展

因为企业后台业务系统的权限和用户、组织机构这些是无法解耦的,而无论是spring security还是shiro对用户的自定义支持有限,对组织机构的支持则一点都没有

用户密码加密

发表于 2018-11-23

采用SHA256加密

SHA-2,名称来自于安全散列算法2(英语:Secure Hash Algorithm 2)的缩写,一种密码散列函数算法标准,由美国国家安全局研发,属于SHA算法之一,是SHA-1的后继者。

SHA256上,说白了,它就是一个哈希函数。

哈希函数,又称散列算法,是一种从任何一种数据中创建小的数字“指纹”的方法。散列函数把消息或数据压缩成摘要,使得数据量变小,将数据的格式固定下来。该函数将数据打乱混合,重新创建一个叫做散列值(或哈希值)的指纹。散列值通常用一个短的随机字母和数字组成的字符串来代表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* SHA256 摘要算法工具类
* @author Administrator
*
*/
public class SHA256Util {

  /**
  * 利用java原生的摘要实现SHA256加密
  * @param str 加密后的报文
  * @return
  */
  public static String getSHA256StrJava(String str){
    MessageDigest messageDigest;
    String encodeStr = "";
    try {
      messageDigest = MessageDigest.getInstance("SHA-256");
      messageDigest.update(str.getBytes("UTF-8"));
      encodeStr = byte2Hex(messageDigest.digest());
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return encodeStr;
  }

  /**
  * 将byte转为16进制
  * @param bytes
  * @return
  */
  private static String byte2Hex(byte[] bytes){
    StringBuffer stringBuffer = new StringBuffer();
    String temp = null;
    for (int i=0;i<bytes.length;i++){
      temp = Integer.toHexString(bytes[i] & 0xFF);
      if (temp.length()==1){
        //1得到一位的进行补0操作
        stringBuffer.append("0");
      }
      stringBuffer.append(temp);
    }
    return stringBuffer.toString();
  }

}

spring security认证过程:
Spring Security认证是由 AuthenticationManager 来管理的,但是真正进行认证的是 AuthenticationManager 中定义的 AuthenticationProvider。

AuthenticationManager 中可以定义有多个 AuthenticationProvider。当我们使用 authentication-provider 元素来定义一个 AuthenticationProvider 时,如果没有指定对应关联的 AuthenticationProvider 对象。

Spring Security 默认会使用 DaoAuthenticationProvider。DaoAuthenticationProvider 在进行认证的时候需要一个 UserDetailsService 来获取用户的信息 UserDetails,其中包括用户名、密码和所拥有的权限等。

所以如果我们需要改变认证的方式,我们可以实现自己的 AuthenticationProvider;如果需要改变认证的用户信息来源,我们可以实现 UserDetailsService。

SQL语句

发表于 2018-11-21 更新于 2018-12-25

W3school

插入
INSERT INTO 表名称 VALUES (值1, 值2,….)
更新
UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
删除
DELETE FROM 表名称 WHERE 列名称 = 值

排序
SELECT Company, OrderNumber FROM Orders ORDER BY Company, OrderNumber
倒序
SELECT Company, OrderNumber FROM Orders ORDER BY Company DESC

去重
SELECT DISTINCT

使用cmd指令
登录 mysql -u root -P3309 -p 实例_data

版本兼容问题
修复 mysql_upgrade –protocol=tcp -P 3309 -u root -p

Usage: mysql [OPTIONS] [database]
-?, –help Display this help and exit.
-I, –help Synonym for -?
–auto-rehash Enable automatic rehashing. One doesn’t need to use
‘rehash’ to get table and field completion, but startup
and reconnecting may take a longer time. Disable with
–disable-auto-rehash.
(Defaults to on; use –skip-auto-rehash to disable.)
-A, –no-auto-rehash
No automatic rehashing. One has to use ‘rehash’ to get
table and field completion. This gives a quicker start of
mysql and disables rehashing on reconnect.
–auto-vertical-output
Automatically switch to vertical output mode if the
result is wider than the terminal width.
-B, –batch Don’t use history file. Disable interactive behavior.
(Enables –silent.)
–bind-address=name IP address to bind to.
–character-sets-dir=name
Directory for character set files.
–column-type-info Display column type information.
-c, –comments Preserve comments. Send comments to the server. The
default is –skip-comments (discard comments), enable
with –comments.
-C, –compress Use compression in server/client protocol.
-#, –debug[=#] This is a non-debug version. Catch this and exit.
–debug-check Check memory and open file usage at exit.
-T, –debug-info Print some debug info at exit.
-D, –database=name Database to use.
–default-character-set=name
Set the default character set.
–delimiter=name Delimiter to be used.
–enable-cleartext-plugin
Enable/disable the clear text authentication plugin.
-e, –execute=name Execute command and quit. (Disables –force and history
file.)
-E, –vertical Print the output of a query (rows) vertically.
-f, –force Continue even if we get an SQL error.
-G, –named-commands
Enable named commands. Named commands mean this program’s
internal commands; see mysql> help . When enabled, the
named commands can be used from any line of the query,
otherwise only from the first line, before an enter.
Disable with –disable-named-commands. This option is
disabled by default.
-i, –ignore-spaces Ignore space after function names.
–init-command=name SQL Command to execute when connecting to MySQL server.
Will automatically be re-executed when reconnecting.
–local-infile Enable/disable LOAD DATA LOCAL INFILE.
-b, –no-beep Turn off beep on error.
-h, –host=name Connect to host.
-H, –html Produce HTML output.
-X, –xml Produce XML output.
–line-numbers Write line numbers for errors.
(Defaults to on; use –skip-line-numbers to disable.)
-L, –skip-line-numbers
Don’t write line number for errors.
-n, –unbuffered Flush buffer after each query.
–column-names Write column names in results.
(Defaults to on; use –skip-column-names to disable.)
-N, –skip-column-names
Don’t write column names in results.
–sigint-ignore Ignore SIGINT (CTRL-C).
-o, –one-database Ignore statements except those that occur while the
default database is the one named at the command line.
-p, –password[=name]
Password to use when connecting to server. If password is
not given it’s asked from the tty.
-W, –pipe Use named pipes to connect to server.
-P, –port=# Port number to use for connection or 0 for default to, in
order of preference, my.cnf, $MYSQL_TCP_PORT,
/etc/services, built-in default (3306).
–prompt=name Set the mysql prompt to this value.
–protocol=name The protocol to use for connection (tcp, socket, pipe,
memory).
-q, –quick Don’t cache result, print it row by row. This may slow
down the server if the output is suspended. Doesn’t use
history file.
-r, –raw Write fields without conversion. Used with –batch.
–reconnect Reconnect if the connection is lost. Disable with
–disable-reconnect. This option is enabled by default.
(Defaults to on; use –skip-reconnect to disable.)
-s, –silent Be more silent. Print results with a tab as separator,
each row on new line.
–shared-memory-base-name=name
Base name of shared memory.
-S, –socket=name The socket file to use for connection.
–ssl Enable SSL for connection (automatically enabled with
other flags).
–ssl-ca=name CA file in PEM format (check OpenSSL docs, implies
–ssl).
–ssl-capath=name CA directory (check OpenSSL docs, implies –ssl).
–ssl-cert=name X509 cert in PEM format (implies –ssl).
–ssl-cipher=name SSL cipher to use (implies –ssl).
–ssl-key=name X509 key in PEM format (implies –ssl).
–ssl-crl=name Certificate revocation list (implies –ssl).
–ssl-crlpath=name Certificate revocation list path (implies –ssl).
–ssl-verify-server-cert
Verify server’s “Common Name” in its cert against
hostname used when connecting. This option is disabled by
default.
-t, –table Output in table format.
–tee=name Append everything into outfile. See interactive help (\h)
also. Does not work in batch mode. Disable with
–disable-tee. This option is disabled by default.
-u, –user=name User for login if not current user.
-U, –safe-updates Only allow UPDATE and DELETE that uses keys.
-U, –i-am-a-dummy Synonym for option –safe-updates, -U.
-v, –verbose Write more. (-v -v -v gives the table output format).
-V, –version Output version information and exit.
-w, –wait Wait and retry if connection is down.
–connect-timeout=# Number of seconds before connection timeout.
–max-allowed-packet=#
The maximum packet length to send to or receive from
server.
–net-buffer-length=#
The buffer size for TCP/IP and socket communication.
–select-limit=# Automatic limit for SELECT when using –safe-updates.
–max-join-size=# Automatic limit for rows in a join when using
–safe-updates.
–secure-auth Refuse client connecting to server if it uses old
(pre-4.1.1) protocol.
(Defaults to on; use –skip-secure-auth to disable.)
–server-arg=name Send embedded server this as a parameter.
–show-warnings Show warnings after every statement.
–plugin-dir=name Directory for client-side plugins.
–default-auth=name Default authentication client-side plugin to use.
–histignore=name A colon-separated list of patterns to keep statements
from getting logged into mysql history.
–binary-mode By default, ASCII ‘\0’ is disallowed and ‘\r\n’ is
translated to ‘\n’. This switch turns off both features,
and also turns off parsing of all clientcommands except
\C and DELIMITER, in non-interactive mode (for input
piped to mysql or loaded using the ‘source’ command).
This is necessary when processing output from mysqlbinlog
that may contain blobs.
–connect-expired-password
Notify the server that this client is prepared to handle
expired password sandbox mode.

Default options are read from the following files in the given order:
C:\WINDOWS\my.ini C:\WINDOWS\my.cnf C:\my.ini C:\my.cnf D:\apm\mysql\my.ini D:\apm\mysql\my.cnf
The following groups are read: mysql client
The following options may be given as the first argument:
–print-defaults Print the program argument list and exit.
–no-defaults Don’t read default options from any option file,
except for login file.
–defaults-file=# Only read default options from the given file #.
–defaults-extra-file=# Read this file after the global files are read.
–defaults-group-suffix=#
Also read groups with concat(group, suffix)
–login-path=# Read this path from the login file.

Variables (–variable-name=value)
and boolean options {FALSE|TRUE} Value (after reading options)


auto-rehash TRUE
auto-vertical-output FALSE
bind-address (No default value)
character-sets-dir (No default value)
column-type-info FALSE
comments FALSE
compress FALSE
debug-check FALSE
debug-info FALSE
database (No default value)
default-character-set auto
delimiter ;
enable-cleartext-plugin FALSE
vertical FALSE
force FALSE
named-commands FALSE
ignore-spaces FALSE
init-command (No default value)
local-infile FALSE
no-beep FALSE
host (No default value)
html FALSE
xml FALSE
line-numbers TRUE
unbuffered FALSE
column-names TRUE
sigint-ignore FALSE
port 0
prompt mysql>
quick FALSE
raw FALSE
reconnect TRUE
shared-memory-base-name (No default value)
socket (No default value)
ssl FALSE
ssl-ca (No default value)
ssl-capath (No default value)
ssl-cert (No default value)
ssl-cipher (No default value)
ssl-key (No default value)
ssl-crl (No default value)
ssl-crlpath (No default value)
ssl-verify-server-cert FALSE
table FALSE
user (No default value)
safe-updates FALSE
i-am-a-dummy FALSE
connect-timeout 0
max-allowed-packet 16777216
net-buffer-length 16384
select-limit 1000
max-join-size 1000000
secure-auth TRUE
show-warnings FALSE
plugin-dir (No default value)
default-auth (No default value)
histignore (No default value)
binary-mode FALSE
connect-expired-password FALSE

数学

发表于 2018-11-20 更新于 2018-12-03

数学

我认为世界的本质是数学,数学可以描述我们所认知的一切。

数学模型就是我们解决问题方式,通过模型计算的结果就是我们针对问题给出的答案

不关心具体结果,只研究关系

预测将要发生的一切,从而做出决策

用变量和函数来研究关系,于算数不同的是。代数不关心结果,只关心变量之间的关系

语言可以用来交流,但更重要的是语言可以描述事务的关系

计数模型-乘法模型

积累因素-积累量 积累因素-积累速度

做向量乘法时 权重的个数必须于因素一致

线性代数

向量(vector) 可用一个向量x=[x1,x2]
权重w=[w1,w2]
偏移d=[d1,d2]
结果y=[y1,y2]

学习

学习就是从有限的例子中找出问题和答案之间规律的一个过程,这个规律就叫做知识

用 知识 - 压缩 消息 得出无限种可能

最终的学习一定要通过例子来理清问题和答案之间的关系

正真的机器学习是让机器自己从例子中发现规律

Spring-Boot的上传

发表于 2018-11-09 更新于 2019-03-12 分类于 IO , 文件流

传参

前端用from表单提交,spring boot 参数已经通过拦截器做好了映射处理

文件上传配置

spring.servlet.multipart.max-request-size=500MB
spring.servlet.multipart.max-file-size=500MB

如果有覆盖总是最下面的生效

自定义配置文件

1
2
property.param.key=key
property.param.name=name

映射类

1
2
3
4
5
6
7
8
9
@Configuration
@PropertySource("classpath:self-config.properties")
@ConfigurationProperties(prefix="property.param")
@Data
@Component
public class FileProperties {
private String key;
private String name;
}

实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@EnableConfigurationProperties(FileProperties.class)
@Service
@Slf4j
public class ServiceImpl implements MultipartFileService{
private final FileProperties fileProperties;
@Autowired
@SuppressWarnings("SpringJavaAutowiringInspection")
public MultipartFileServiceImpl(FileProperties fileProperties) {
this.fileProperties = fileProperties;
}

public void test(){
log.info(fileProperties.getKey+fileProperties.getName);
}
}

文件上传实现返回上传路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private String saveFile(MultipartFile file,String fileType,String fileName){
//读取配置文件,获取文件上传路径
Path path= Paths.get(fileProperties.getUploadPath(fileType)+ fileName);
File targetFile=path.toFile().getParentFile();
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
byte[] bytes = file.getBytes();
Files.write(path,bytes);
}catch (Exception e){
log.error(e.getMessage(),e);
return null;
}
return path.toString();
}

Nginx

发表于 2018-11-06 更新于 2018-12-26

Nginx是什么?

Nginx 是俄罗斯人编写的十分轻量级的 HTTP 服务器,Nginx,它的发音为“engine X”,是一个高性能的HTTP和反向代理服务器,同时也是一个 IMAP/POP3/SMTP 代理服务器。
到 2013 年,目前有很多国内网站采用 Nginx 作为 Web 服务器,如国内知名的新浪、163、腾讯、Discuz、豆瓣等。据 netcraft 统计,Nginx 排名第 3,约占 15% 的份额

Nginx 以事件驱动的方式编写,所以有非常好的性能,同时也是一个非常高效的反向代理、负载平衡。其拥有匹配 Lighttpd 的性能,同时还没有 Lighttpd 的内存泄漏问题,
而且 Lighttpd 的 mod_proxy 也有一些问题并且很久没有更新。现在,Igor 将源代码以类 BSD 许可证的形式发布。Nginx 因为它的稳定性、丰富的模块库、灵活的配置和
低系统资源的消耗而闻名.业界一致认为它是 Apache2.2+mod_proxy_balancer 的轻量级代替者,不仅是因为响应静态页面的速度非常快,而且它的模块数量达到 Apache
的近 2/3。对 proxy 和 rewrite 模块的支持很彻底,还支持 mod_fcgi、ssl、vhosts ,适合用来做 mongrel clusters 的前端 HTTP 响应。

node.js则是一个JavaScript运行环境

启动

start nginx

停止

nginx.exe -s stop
D:\nginx-1.0.2\nginx.exe -s quit
stop是强制退出 quit是有序退出

重启

nginx -s reload

服务监听真实ip

proxy_set_header X-Real-IP $remote_addr;             # 远端真实ip地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 反向代理之后转发之前的ip地址
proxy_set_header Host $http_host;                  # http请求的主机域名
proxy_set_header X-NginX-Proxy true;                # nginx代理

websocket配置,通讯转发

location /wse{
proxy_pass http://127.0.0.1:8086;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;

proxy_read_timeout 60s;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

前端路由配置服务器配置

服务器需要做好处理 URL 的准备。处理应用启动最初的 / 这样的请求应该没问题,但当用户来回跳转并在 /accounts/123 刷新时,服务器就会收到来自 /accounts/123 的请求,这时你需要处理这个 URL 并在响应中包含 JavaScript 应用代码。

一个 express 的应用可能看起来像这样的:

const express = require(‘express’)
const path = require(‘path’)
const port = process.env.PORT || 8080
const app = express()

// 通常用于加载静态资源
app.use(express.static(__dirname + ‘/public’))

// 在你应用 JavaScript 文件中包含了一个 script 标签
// 的 index.html 中处理任何一个 route
app.get(‘*’, function (request, response){
response.sendFile(path.resolve(__dirname, ‘public’, ‘index.html’))
})

app.listen(port)
console.log(“server started on port “ + port)
如果你的服务器是 nginx,请使用 try_files 指令:

server {
…
location / {
try_files $uri /index.html
}
}
当在服务器上找不到其他文件时,这可以让 nginx 服务器提供静态文件服务并指向index.html 文件。

对于Apache服务器也有类似的方式,创建一个.htaccess文件在你的文件根目录下:

RewriteBase /
RewriteRule ^index.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

常见错误

nginx: [error] OpenEvent(“Global\ngx_reload_2380”) failed (2: The system cannot find the file specified)

nginx未启动重启nginx就可以了

负载均衡 几种常用方式

1、轮询(默认)
每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
upstream backserver {
server 192.168.0.14;
server 192.168.0.15;
}

2、weight(权重)
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
upstream backserver {
server 192.168.0.14 weight=3;
server 192.168.0.15 weight=7;
}

3、ip_hash;
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,
可以解决session的问题
upstream backserver {
ip_hash;
server 192.168.0.14:88;
server 192.168.0.15:80;
}

4、fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream backserver {
server server1;
server server2;
fair;
}

5、url_hash(第三方)
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,
后端服务器为缓存时比较有效。
upstream backserver {
server squid1:3128;
server squid2:3128;
hash $request_uri;
hash_method crc32;
}
node.js非阻塞和事件驱动

批处理命令

发表于 2018-11-02 更新于 2018-11-16

批处理命令

1
2
3
4
echo "批处理文件 echo是输出的意思"
echo "当前目录"%cd%
echo "脚本自身目录"%~dp0
pause

pause是暂停的意思不让命令行一闪而过 有中文时编码用ANSI 防止乱码

1
@echo off

echo off 是不显示命令的意思 加上@是这条命令本身也不显示
REM 有输出的注释
:: 无输出的注释

切换磁盘

1
cd /d D:

执行其他批处理命令

start d:\1.bat
call c:\2.bat

start是在新的窗口执行任务,call是在当前窗口执行,执行完了才执行下面的语句

检查端口占用情况

GOTO check80

:check80
echo check port 80…
for /f “tokens=3 delims=:, “ %%i in (‘netstat -ano’) do (
if “%%i” == “80” GOTO 80used
)
GOTO check21

:80used
mshta vbscript:CreateObject(“Wscript.Shell”).popup(“端口80被占用,请解除端口占用后重新启动”,7,”提示”,64)(window.close)
exit /B 2

Spring-Boot 企业级安装程序

发表于 2018-10-26 更新于 2019-02-19

需求

spring-boot 生成企业级安装程序,主要要求程序在windows下一键安装开机自启,这类的博客很少,基本只能自己摸索了。

思路

Springboot自带tomcat 只用启动-jar demo-0.0.1-SNAPSHOT.jar就可以启动项目了,然后在同目录下安装jre环境,说明java运行环境,配置好数据库就可以了。这里还是考虑用Tomcat+Nginx 来部署,方便以后的调试和扩展,而且配置更全面一些。

下载apache-tomcat-8 将打好的war包放在webapp中 可以改配置放在其他文件夹
前台的包可以放在nginx的html目录下 这两个包都可以通过配置文件来更改存储位置。

分为两部,第一部分是安装程序Stepup.exe(安装mysql,初始化数据库,获取项目路径,修改项目),第二步骤才是运行Start.exe(运行批处理文件)

使用工具

JDK1.8,MySQL5.7,Tomcat8,Nginx,BatToExeConverter等,这是需要压缩的文件资源。

也可以考虑用到Inno Setup

mysql部分

MySQL需要配置环境变量的原因是因为但是每次都切换到安装目录下太麻烦,如果不嫌弃麻烦可以直接在目录执行,这里我们就直接
跳转到安装路径执行需要的命令

安装服务

rem 进入mysql目录
cd “%~dp0”..\mysql-5.7.24-win32\bin”
rem 初始化 –必不可少
mysqld –initialize-insecure
rem 先移除服务
mysqld –remove “服务名”
rem 安装服务
mysqld -install “服务名”

my.ini

my.ini配置如下可以在批处理文件中写入,文件保存为ANSI格式文件,不然初始化报错,端口配置一个使用较少的3309
减少冲突的概率,当然还是要进行端口重复检查
[mysql]
default-character-set=utf8
[mysqld]
port = 3309
basedir=D:\mysql-5.7.24-win32
datadir=D:\mysql-5.7.24-win32\data
max_connections=200
character-set-server=utf8
default-storage-engine=INNODB

端口占用检查

echo check port 3309…
for /f “tokens=3 delims=:, “ %%i in (‘netstat -ano’) do (
if “%%i” == “3309” GOTO 3309used
)

:3309used
mshta vbscript:CreateObject(“Wscript.Shell”).popup(“端口3309被占用,请解除端口占用后重新启动”,7,”提示”,64)(window.close)
exit /B 2

启动服务脚本如下

net stop “服务名”
net start “服务名”

登陆测试

mysql -u root -ppassword

Tomcat部分

修改端口,修改访问路径

server.xml

修改端口为”8086”

修改项目访问路径,缩减项目访问路径,path代表映射路径 docBase代表项目路径 workDir表示缓存文件位置

配置环境变量

修改TOMCAT_HOME\bin\setclasspath.bat文件
set JAVA_HOME=D:\jdk1.8\
set JRE_HOME=D:\jdk1.8\jre

隐藏执行窗口

(1)修改脚本
setclasspath.bat文件
rem set _RUNJAVA=”%JRE_HOME%\bin\javaw” (隐藏文件)
set _RUNJAVA=”%JRE_HOME%\bin\java.exe”

(2)注册成服务
cmd cd tomcat\bin
service.bat install [serviceName]
在此种方案中部署程序,该程序访问不到网络盘

自启动

这里采用(2)方便配置自启动
修改启动方式,在windows服务下设置成自启动,将mysql服务设置成依赖服务

Nginx部分

代理和请求转发的概念是相对的,我通过Nginx发送一条请求到服务器,我到服务器的过程就叫做代理,服务器响应的信息通过Nginx转发到我就叫做反向代理,而Nginx的这一动作就叫做请求转发

做服务器的时候还有安全策略配置,公网私网访问设置,主要是防火墙方面的配置,这点linux也一样。

Nginx配置

请求转发

1
2
3
location /api{
proxy_pass http://127.0.0.1:8086;
}

首页配置

1
2
3
4
location /{
root D:\DSCMS\app\html;
index index.html index.htm;
}

websocket nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
location /wse{
proxy_pass http://127.0.0.1:8080;

#websocket服务通过nginx转发
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

#获取请求真实地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

Nginx指令

所有安装指令基于nginx的安装目录下

Nginx关闭 nginx -s stop (立刻停止) 或者 nginx -s quit (正常停止)
Nginx启动 start nginx
Nginx重启 Nginx -s reload (修改配置nginx.conf后使用)

window下无法正常停止Nginx进程
使用taskkill /im nginx.exe /f

开启自启动

将 windows 服务设置成自启动
bat文件转为exe,将bat文件设置

sc delete ServiceName

sc create ServiceName binpath= D:\DSCMS\start.exe type= own start= auto displayname= DSCMSServices

net start ServiceName

net stop ServiceName

使用jar包部署环境
jre路径/ -jar demo-1.0.jar

1…3456

fsh

54 日志
4 分类
20 标签
© 2019 fsh
由 Hexo 强力驱动 v3.9.0
|
主题 – NexT.Pisces v7.3.0