邢栋博客

邢栋博客,Action博客,记录工作和生活中的点点滴滴

mysql锁简记
锁分类
1.读锁(共享锁,读操作不受影响,别的会话有插入操作会处于阻塞状态) 写锁(排他锁,在写操作完成之前,会阻断其他读和写操作)
2.表锁和行级锁

======1.表锁 偏读========
myisam存储引擎,开销小,加锁快,锁力度大,发生锁冲突的概率最高,并发度最低

//手动加锁
lock table 表名称 read(write),表名称2 read(write),其他;
//查看表上加过的锁
show open tables;
//删除表锁
unlock tables;
//分析表锁定
show status like 'table%';
 Variable_name              | Value |
+----------------------------+-------+
| Table_locks_immediate      | 112   |//产生表级锁定的次数,表示可以立即获取锁的查询次数,每立即获取锁值加1 
| Table_locks_waited         | 0     | //出现表级锁定争用而发生等待的次数(不能立即获取锁的次数,每等待一次锁值加1),此值高则说明存在着较严重的表级锁争用情况。
| Table_open_cache_hits      | 0     |
| Table_open_cache_misses    | 6     |//在打开表时,表缓存不存在的次数。
| Table_open_cache_overflows | 0 |


======2.行锁 偏写========
行锁偏向InnoDB存储引擎,开销大,加锁慢,会出现死锁,锁定粒度最小,发生锁冲突的概率最低,并发度也最高。
InnoDB与MYISAM的最大不同有两点:一是支持事务(TRANSACTION);二是采用了行级锁。

事务特性:原子性Atomicity,一致性Consistent,隔离性lsolation,持久性Durable

1.set autocommit=0;update ......;commit;
2.间隙锁
当我们用范围条件而不是相等条件检索数据,并请求共享或排他锁,Innodb会给符合条件的已有数据记录的索引加锁;对于键值在条件范围内但不存在的记录,叫做间隙
(GAP);Innodb也会对这个间隙加锁,
危害:因为query执行过程中通过范围查找的话,他会锁定整个范围所有的索引值,即使这个键值并不存在。
行锁分析:
show status like 'innodb_row_lock%';
+-------------------------------+-------+
| Variable_name                 | Value |
+-------------------------------+-------+
| Innodb_row_lock_current_waits | 0     |当前正在等待锁定的数量 
| Innodb_row_lock_time          | 0     |从系统启动到现在锁定总时间长度 ***
| Innodb_row_lock_time_avg      | 0     |每次等待所花平均时间 ***
| Innodb_row_lock_time_max      | 0     |从系统启动到现在等待最长的一次所花时间 
| Innodb_row_lock_waits         | 0    |系统启动后到现在总共等待的次数 ***


优化建议
1.尽可能让所有数据检索都通过索引来完成,避免无索引行锁升级为表锁
2.合理设计索引,尽量缩小锁的范围
3.尽可能减少检索条件,避免间隙锁
4.尽量控制事务大小,减少锁定资源量和时间长度
5.s尽可能低级别事务隔离


======3.页面锁 偏写========
开销和加锁时间界于表锁和行锁之间;会出现死锁;锁定粒度界于表锁和行锁之间,并发度一般


==================================
共享锁(S):SELECT * FROM table_name WHERE ... LOCK IN SHARE MODE。
排他锁(X):SELECT * FROM table_name WHERE ... FOR UPDATE。
InnoDB这种行锁实现特点:只有通过索引条件检索数据,InnoDB才使用行级锁,否则,InnoDB将使用表锁!
数据结构之数组和链表
====数组=====
1.在内存中,数组是一块连续的区域
2.数组需要预留空间,在使用前需要提前申请所占内存的大小
3.在数组起始位置处,插入数据和删除数据效率低
-插入数据时,待插入位置的元素和它后面的所有元素都需要向后搬移
-删除数据时,待删除位置后面的所有元素都要向前搬移
4.随机访问速度效率很高,时间复杂度可以到达O(1)
因为数组的内存是连续的,想要访问那个元素,直接从数组的首地址向后偏移就可以访问到了
5.数组开辟的空间,在不够使用的时候需要扩容,扩容的话,就会涉及需要把旧数组的所有数据向新数组中搬移
6.数组的空间是从栈分配的
====数组的优点====
随机访问性强,查找速度快,时间复杂度O(1)
====数组的缺点====
1.头插和头删的效率低,时间复杂度O(N)
2.空间利用率不高
3.内存空间要求高,必须有足够的连续的内存空间
4.数组空间的大小固定,不能动态扩展


=====链表=====
1.在内存中,元素的空间可以在任意地方,空间是分散的,不需要连续 
2.链表中的元素都会两个属性,一个是元素的值,另一个是指针,此指针标记了下一个元素的地址
每一个数据都会保存下一个数据的内存的地址,通过此地址可以找到下一个数据
3.查找数据时效率低,时间复杂度为O(N)
因为链表的空间是分散的,所以不具有随机访问性,如要需要访问某个位置的数据,需要从第一个数据开始找起,依次往后遍历,直到找到待查询的位置,故可能在查找某个元素时,时间复杂度达到O(N)
4.空间不需要提前指定大小,是动态申请的,根据需求动态的申请和删除内存空间,扩展方便,故空间的利用率较高 
5.任意位置插入元素和删除元素效率较高,时间复杂度为O(1) 
6.链表的空间是从堆中分配的
====链表的优点====
1.任意位置插入元素和删除元素的速度快,时间复杂度为O(1) 
2.内存利用率高,不会浪费内存 
3.链表的空间大小不固定,可以动态拓展

====链表的缺点====
随机访问效率低,时间复杂度为0(N)

centos7下gcc升级
=====下载地址=====
https://ftp.gnu.org/gnu/gcc/

=====下载gcc和相关依赖=====
wget https://ftp.gnu.org/gnu/gcc/gcc-5.4.0/gcc-5.4.0.tar.gz
tar -zxvf gcc-5.4.0.tar.gz
cd gcc-5.4.0
./contrib/download_prerequisites //相关依赖


=====建立存放编译文件的文件夹+编译=====
mkdir gcc-build-5.4.0
cd gcc-build-5.4.0/
../configure --prefix=/usr/local/gcc5 --enable-languages=c,c++,go  --disable-multilib
make  //耗时很长很长
make install 

=====复制命令=====
rm -f /usr/bin/gcc
rm -f /usr/bin/g++
ln -s /usr/local/gcc5/bin/gcc /usr/bin/gcc
ln -s /usr/local/gcc5/bin/g++ /usr/bin/g++


=====关联新的动态库=====
cd /usr/local/gcc5/lib64/
cp libstdc++.so.6.0.21 /usr/lib64/
rm -rf /usr/lib64/libstdc++.so.6
ln -s libstdc++.so.6.0.21 libstdc++.so.6
centos7查看开机启用服务列表以及启用禁用相关服务
查看开机启动服务列表
systemctl list-unit-files
systemctl list-unit-files |grep php
加入启动
systemctl enable postfix
启动
systemctl start postfix
停止
systemctl stop postfix
禁用
systemctl disable postfix
状态
systemctl status postfix
centos7下安装gitlab问题总结
=====问题1 执行 systemctl start  postfix
Job for postfix.service failed because the control process exited with error code. See "systemctl status postfix.service" and "journalctl -xe" for details.=====

解决方法
vim /etc/postfix/main.cf 
myhostname = mail.flycoder.cn
mydomain = flycoder.cn
myorigin = $mydomain
inet_interfaces = localhost // all表示接受来自所有网络的请求
mydestination = $myhostname, localhost.$mydomain, localhost  //指定发给本地邮件的域名
inet_protocols = ipv4
centos7下安装gitlab并修改访问端口
centos7下安装gitlab并修改访问端口

官网安装说明
https://about.gitlab.com/install/#centos-7

1.=======================
sudo yum install -y curl policycoreutils-python openssh-server
sudo systemctl enable sshd
sudo systemctl start sshd
sudo firewall-cmd --permanent --add-service=http
sudo systemctl reload firewalld

2.=======================
sudo yum install postfix
sudo systemctl enable postfix
sudo systemctl start postfix

3.=======================
curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh | sudo bash
yum install -y gitlab-ee
gitlab-ctl reconfigure //如果没有启动gitlab再执行,我的没有启动

ps:这个时候就可以通过服务器的地址直接访问了,第一次进入需要修改密码,用户名root


4.=======启动/暂停/重启=======
gitlab-ctl start
gitlab-ctl stop
gitlab-ctl restart


5.=========修改端口=============

vim /etc/gitlab/gitlab.rb
external_url 'http://我的服务器地址:8081'
nginx['listen_port'] = 8081

vim /var/opt/gitlab/nginx/conf/gitlab-http.conf
listen *:8081;
server_name localhost;
if ($http_host = "") {
set $http_host_with_default "localhost:8081";
}
然后执行
gitlab-ctl restart 
springboot2.X集成es5.5
==========pom.xml==============
1.修改内容
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>5.5.2</elasticsearch.version>
</properties>

2.修改内容
<!-- ES elasticsearch -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.0</version>
</dependency>


=======增加MyEsConfig.java=============


package com.action.firstappdemo.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author Action
 * @Description:
 * @Date Create in 2019/5/5 15:21
 */
@Configuration
public class MyEsConfig {

    @Bean
    public TransportClient client() throws UnknownHostException {

        InetSocketTransportAddress node = new InetSocketTransportAddress(
                InetAddress.getByName("localhost"),
                9300
        );
        InetSocketTransportAddress node1 = new InetSocketTransportAddress(
                InetAddress.getByName("localhost"),
                9301
        );
        InetSocketTransportAddress node2 = new InetSocketTransportAddress(
                InetAddress.getByName("localhost"),
                9302
        );

        Settings settings = Settings.builder()
                .put("cluster.name", "action")
                .build();

        TransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddress(node);
        client.addTransportAddress(node1);
        client.addTransportAddress(node2);

        return client;

    }

}

======EsController.java 增删改查===============

package com.action.firstappdemo.controller;

import com.imooc.firstappdemo.common.PageBean;
import com.imooc.firstappdemo.entity.DataAppDpi;
import com.imooc.firstappdemo.service.IconService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.n3r.idworker.Sid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * mvn spring-boot:run
 */
@Slf4j
@Controller
@RequestMapping("es")
public class EsController {

    @Autowired
    private TransportClient client;

    @RequestMapping("/get/people/man")
    @ResponseBody
    public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id){
        if(id.isEmpty()){
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        //prepareGet预执行
        GetResponse result = client.prepareGet("people", "man", id).get();
        if(! result.isExists()){
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(result.getSource(), HttpStatus.OK);
    }

    @RequestMapping("/add/people/man")
    @ResponseBody
    public ResponseEntity add(@RequestParam(name = "name") String name, @RequestParam(name = "age") int age, @RequestParam(name = "date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date, @RequestParam(name = "country") String country){
        try {
            XContentBuilder content = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("name", name)
                    .field("age", age)
                    .field("date", date.getTime())
                    .field("country", country)
                    .endObject();
            // prepareIndex构建索引
            IndexResponse result = client.prepareIndex("people", "man")
                    .setSource(content)
                    .get();
            return new ResponseEntity(result.getId(), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @RequestMapping("/del/people/man")
    @ResponseBody
    public ResponseEntity del(@RequestParam(name = "id") String id){
        DeleteResponse result = client.prepareDelete("people", "man", id).get();
        return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);

    }

    @RequestMapping("/update/people/man")
    @ResponseBody
    public ResponseEntity update(@RequestParam(name = "id") String id, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "age", required = false) Integer age, @RequestParam(name = "date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date, @RequestParam(name = "country", required = false) String country){
        UpdateRequest update = new UpdateRequest("people", "man", id);
        try {
            XContentBuilder content = XContentFactory.jsonBuilder().startObject();
            if(null != name){ content.field("name", name); }
            if(null != age){ content.field("age", age); }
            if(null != date){ content.field("date", date); }
            if(null != country){ content.field("country", country); }
            content.endObject();
            update.doc(content);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        try {
            UpdateResponse result = client.update(update).get();
            return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @RequestMapping("/query/people/man")
    @ResponseBody
    public ResponseEntity query(@RequestParam(name = "name", required = false) String name, @RequestParam(name = "gt_age", defaultValue = "0") Integer minAge, @RequestParam(name = "lt_age", required = false) Integer maxAge){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(null != name){
            boolQuery.must(QueryBuilders.matchQuery("name", name));
        }
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age").from(minAge);

        if(null != maxAge && 0 < maxAge){ rangeQuery.to(maxAge); }
        boolQuery.filter(rangeQuery);
        SearchRequestBuilder builder = client.prepareSearch("people")
                .setTypes("man")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQuery)
                .setFrom(8)
                .setSize(10);

//        System.out.println(builder);
        SearchResponse response = builder.get();
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for(SearchHit hit : response.getHits()){
            result.add(hit.getSource());
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

}

windows和mac下安装java并配置路径
进入
https://www.oracle.com/technetwork/java/javase/downloads/index.html
下载对应的平台+版本的安装包

====WINDOWS平台下====== 公用JRE 不用安装

我的电脑--属性--高级系统设置 --环境变量
配置环境遍历
JAVA_HOME D:\Program Files\Java\jdk1.8.0_201
PATH 加入 D:\Program Files\Java\jdk1.8.0_201\bin
CLASSPATH .;D:\Program Files\Java\jdk1.8.0_201\lib



====MAC平台下====== 
查看java_home 
/usr/libexec/java_home -V
加入环境变量
vim /etc/profile
JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home"
export JAVA_HOME
CLASS_PATH="$JAVA_HOME/lib"
PATH=".$PATH:$JAVA_HOME/bin"
执行
source /etc/profile


优惠券
广告位-淘宝
最新微语