St. Regis Takeaway Linux & Redis

1. Introduction to Linux

Linux system version
The Linux system is divided into kernel version and release version         . Kernel version
:         developed by
        Linus Torvalds and his team, maintenance         is free
        , and open source
        is responsible for controlling hardware. Version



2. Linux installation

Linux system installation method
Physical machine installation: directly install the operating system on the server hardware
Virtual machine installation: install through virtual machine software
 

3. Network card

ip addr

 3.1 Network card settings

 3.2 Install SSH connection tool

SSH (Secureshell), a security protocol based on the application layer

Enterprise linux is installed on the server and requires us to connect remotely.

Use: xshell

4. Catalog introduction

5. Installation method 

 5.1 install jdk

//注意jdk的位置
JAVA_HOME=/usr/local/jdk1.8.0_171
PATH=$JAVA_HOME/bin:$PATH

 5.2 Install Tomcat

 5.2.1 Whether the verification is successful


 

5.2.2 Firewall operation

View firewall status

systemctl status firewalld

or

firewall-cmd --state


Temporarily turn off the firewall

systemctl stop firewalld


Permanently turn off the firewall

systemctl disable firewalld


Turn on the firewall

systemctl start firewalld


open designated ports

firewall-cmd --zone=public --add-port=8080/tcp --permanent


Close the specified port

firewall-cmd --zone=public --remove-port=8080/tcp --permanent


Effective immediately

firewall-cmd --reload


Check open ports

firewall-cmd --zone=public --list-ports

Note:
1. systemct is a command to manage services in Linux. It can start, stop, restart, view status and other operations on services. 2.
firewall-cmd is a command specially used to control firewalls in Linux.
3. In order to ensure system security, the server It is not recommended to close the firewall




5.2.3 Ways to stop Tomcat service:

① Run the script file shutdwnoch provided in the bin directory of Tomcat to stop the service

sh shutdown.sh

./shutdown.sh

②End the Tomcat process
View the Tomcat process and get the process id

 ps -ef | grep tomcat


 

Note:
The kill command is a command provided by Linux to end a process, and -9 means a forced end


 5.3 Install MySQL

①: Detect whether the MySQL database is installed in the current system

rpm -qa

Query all software installed in the current system

rpm -qa | grep mysql
Query the software with mysql in the name installed in the current system


rpm -qa | grep mariadb
Query the software with the name mariadb installed in the current system

RPM (Red-Hat Package Manager) RPM package manager is a tool used by Red Hat Linux to manage and install software
Notes:

If the MySQL database has already been installed in the current system, the installation will fail. Centos7 comes with mariadb, which is flush with the MySQL database
 ②: Uninstall the conflicting software that has been installed

rpm -e --nodeps software name uninstall software
rpm -e --nodeps mariadb-libs-5.5.60-1.el7_5.×86_64

③: Upload the MySQL installation package provided in the data to Linux and decompress it

mkdir /usr/loca/mysql
tar-zxvf mysql-5.7.25-1.el7.x86_64.rpm-bundle.tar.gz-c /usr/local/mysql
 

 ④: Install rpm packages in order

rpm -ivh mysql-community-common-5.7.25-1.el7.x86_64.rpm
rpm -ivh mysql-community-libs-5.7.25-1.el7.x86_64.rpm
rpm -ivh mysql-community-devel-5.7.25-1.el7.x86_64.rpm
rpm -ivh mysql-community-libs-compat-5.7.25-1.el7.x86_64.rpm
rpm -ivh mysql-community-client-5.7.25-1.el7.x86_64.rpm
yum install net-tools
rpm -ivh mysql-community-server-5.7.25-1.el7.x86_64.rpm


Detect dependency failed:

Caused by yum installing an old version of gpg keys

Add "--force --nodeps" to the suffix

eg:

 rpm -ivh mysql-community-common-5.7.25-1.el7.x86_64.rpm --force --nodeps

Note 1: During the installation process, it prompts that the net-tools dependency is missing, use yum to install
Note 2: You can upgrade the existing software and system kernel through instructions

yum update 

⑤: Start mysql ( be careful not to paste spaces )

systemctl status mysqld View mysql service status
systemctl start mysqld Start mysql service
systemctl enable mysqld Start mysql service

netstat -tunlp or netstat -tunlp l grep mysql View started services                            
ps -ef | grep mysql View mysql process

⑥Log in to the MySQL database and check the temporary password
 

cat /var/log/mysqld.log view the file content
cat /var/log/mysqld.log | grep password view the line information containing password in the file content

Notice:

[Note] A temporary password is generated for root@localhost: IAzt_RVda7sD

After the colon is the password, pay attention to the space (no space)

⑦: Log in to MySQL, change the password, and open access rights

mysql -uroot -p log in to mysql (login with a temporary password)

#Modify the password
set global validate_password_length=4; set the minimum number of digits in the password length
set global validate_password_policy=Low; set the password security level is low, so that the password can be changed to root
set password = password('root'); set the password to root

#Open access
grant all on *.* to 'root'@'%'identified by 'root';
flush privileges;
  refresh permissions

⑧: Test whether the MySQL database is working normally

show databases;

5.4 Install lrzsz

1. Search for the lrzsz installation package, the command is yum list lrzsz 

2. Use the yum command to install online, the command is yum install lrzsz.x86_64

Notice: 

Yum (full name YellowdogUpdater, Modified) is a Shell front-end package manager in Fedora, RedHat and CentOs. Based on RPM package management, it can automatically download and install RPM packages from a specified server, automatically handle dependencies, and install all dependent software packages at one time, without the need for complicated downloads and installations.
 

6. Project deployment


6.1 Manual deployment project (complex)

Manually package and upload the jar package. run by command

 ①: Develop the SpringBoot project in IDEA and package it into a jar package

②: Upload the jar package to the Linux server 

eg: mkdir /usr/local/app
creates a directory and puts the project jar package in this directory

③: Start the SpringBoot program

java -jar jar package name

 ④: Check the firewall to ensure that port 8080 is open to the outside world and access the SpringBoot project

Use the firewall part of the command

⑤: Run the SpringBoot program in the background instead, and output the log to the log file (it can still run after linux is closed)

 &>: log file name (created in the current directory)

&: Indicates that the program is executing in the background

eg:nohup java -jar jar package name &> log file name&

Problems with the current program running:

        a. The online program will not run the program in the form of a console dominating the screen, but will run the program in the background
        b. The online program will not output the log to the console, but to the log file, which is convenient for operation and maintenance to consult information

⑥: Stop the SpringBoot program

query process

ps -ef | grabbed java

delete

The process number corresponding to kill -9


6.2 Automatically deploy projects through She scripts


 

 ①: Install Git in Linux
yum list git list git installation package
yum install git install git online

 ②: Use Git to clone the code

cd /usr/local
git clone https://gitee.com/chuanzhiBoke/hellowortd.git

③: Upload the maven installation package provided in the data to Linux, and install maven in Linux 

tar -zxvf apache-maven-3.5.4-bin.tar.gz -C /usr/local/

---------------------------------------------------------------

vim /etc/profile Modify the configuration file to add the following content

export MAVEN_HOME=/usr/local/apache-maven-3.5.4
export PATH=$JAVA_HOME/bin:$MAVEN_HOME/bin:$PATH

---------------------------------------------------------------

source /etc/profile

mvn -version

---------------------------------------------------------------

Modify the configuration file

vim /usr/local/apache-maven-3.5.4/conf/settings.xml 

as follows:

<localRepository>/usr/local/repo</localRepository>

④: Copy the Shell script file provided in the data to Linux

#!/bin/sh
echo =================================
echo  自动化部署脚本启动
echo =================================

echo 停止原来运行中的工程
APP_NAME=helloworld

tpid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
    echo 'Stop Process...'
    kill -15 $tpid
fi
sleep 2
tpid=`ps -ef|grep $APP_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
    echo 'Kill Process!'
    kill -9 $tpid
else
    echo 'Stop Success!'
fi

echo 准备从Git仓库拉取最新代码
cd /usr/local/helloworld

echo 开始从Git仓库拉取最新代码
git pull
echo 代码拉取完成

echo 开始打包
output=`mvn clean package -Dmaven.test.skip=true`

cd target

echo 启动项目
nohup java -jar helloworld-1.0-SNAPSHOT.jar &> helloworld.log &
echo 项目启动完成

 ⑤ Authorize users

 

⑦: Set static ip

modify file

vim /etc/sysconfig/network-scripts/ifcfg-ens33

⑧Restart network service

systemctl restart network

 Note : After restarting the network service, the ip address has changed. At this time, Finalshell cannot connect to the Linux system.
A new connection needs to be created to connect to Linux.

2、Redis

Redis is a memory - based key-value structured database.

1. Getting Started with Redis

Can be used as: database, cache and messaging middleware.

Complementary to relational databases

Windows version download address: https://github.com/microsoftarchive/redis/releases
Linux version download address: Index of /releases/ (redis.io)

Steps to install Redis on Linux system :

1. Upload the Redis installation package to Linux
2. Decompress the installation package, command: tar -zxvf redis-4.0.0.tar.gz -C /usr/local
3. Install Redis dependent environment gcc, command: yum install gcc- c++
4. Enter /usr/local/redis-4.0.0, compile, command: make
5. Enter the src directory of redis, install, command: make install        

Start and stop of redis service in linux:

Redis service starts in Linux, you can use redis-server

The default port number is 6379

Ctrl+C to stop the Redis service

Background execution: Modify the daemonize in the configuration file redis.conf in the main directory to yes

Then execute src/redis-server ./redis.conf to run in the background

other:

PID: process

redis-cli under src: connect to the client

Edit Mode: /Find Content

Modify the login client with a password to modify redis.conf

Add: requirepass password

eg:requirepass 123456

When the client queries for login: auth password 

When starting the client: src/redis-cli -h localhost -p 6379 -a password (123456)

eg:auth 123456

Switch database default 16 0--15

select (dbid) database name 

------------------------------------------------------------------------------------------------------------------------ 

The Windows version of Redis is a green software that can be used directly after decompression. The directory structure after decompression is as follows:

2. Data type

The data of the key-value structure, where the key is a string type, and the value has 5 commonly used data types

3. Common commands


Redis Chinese Network

1. String operation command

SET key value Set the value of the specified key/overwrite the previous value with the same key
GET key Get the value of the specified key
SETEX key seconds value Set the value of the specified key and set the expiration time of the key to seconds
SETNX key value only when the key does not exist Set the value of the key

127.0.0.1:6379> set name wyh
OK
127.0.0.1:6379> get name
"wyh"


2. Hash hash operation command

Redishash is a mapping table of string type field and value, hash is especially suitable for storing objects
 

HSET key field value Set the value of the field field in the hash table key to value
HGET key field Get the value stored in the specified field in the hash table
HDEL key field Delete the specified field stored in the hash table
HKEYS key Get the hash All fields in the table
HVALS key Get all the values ​​in the hash table
HGETALL key Get all the fields and values ​​of the specified key in the hash table


3. List list operation command


4. Collection set operation command


5. Ordered set sortedset operation command

6. Common commands

4. Operate Redis in java

4.1 Basic use

1. Maven coordinates of Jedis:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.0</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

2. Create a test class

/**
 * Use jedis to operate Redis
 */
public class JedisTest {

    @Test
    public void testRedis(){
        //1 get connection
        Jedis jedis = new Jedis("localhost",6379);
        //2, perform specific operations
            //set up
        jedis.set("username","xiaoming");

        String value = jedis.get("username");
        System.out.println(value);

            //delete
        jedis.del("username");

            //hash
        jedis.hset("myhash","addr","bj");
            // get the value
        String hValue = jedis.hget("myhash","addr");
        System.out.println(hValue);

        //Query all
        Set<String> keys = jedis.keys("*");
        for (String key : keys){
            System.out.println(key);
        }
        //3 close the connection
        jedis.close();
    }
}

4.2 Spring Data Redis (commonly used)

In the SpringBoot project, you can use SpringDataRedis to simplify Redis operations

1. Import coordinates 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

 Step 1: Configure class application.yml

spring:
  application:
    name:java_redis
  #redis相关配置
  redis:
    host:localhost
    port:6379
    #passwoerd:
    database:0 #操作的是0号数据库
    jedis:
      #Redis连接池配置
      pool:
        max-active: 8 #最大连接数
        max-wait: 1ms #连接池最大阻塞等待时间
        max-idle: 4 #连接池中的最大空闲连接
        min-idle: 0 # 连接池中的最小空闲连接

Step 2: The reids database cannot be queried.

Reason: Serialization

Solution: Create a configuration class to modify serialization

SpringDataRedisTest
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataRedisTest {

    //操作不同的接口就需要这个redisTemplate对象
    //此处的redisTemplate对象是我们修改过的
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 操作String类型数据
     */
    @Test
    public void testString(){
        redisTemplate.opsForValue().set("city123","beijing");

        String value = (String) redisTemplate.opsForValue().get("city123");
        System.out.println(value);
    
//long型加l
        redisTemplate.opsForValue().set("key1","value1",10l, TimeUnit.SECONDS);

        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("city1234", "nanjing");
        System.out.println(aBoolean);
    }

    /**
     * 操作Hash类型数据
     */
    @Test
    public void testHash(){
        HashOperations hashOperations = redisTemplate.opsForHash();

        //存值
        hashOperations.put("002","name","xiaoming");
        hashOperations.put("002","age","20");
        hashOperations.put("002","address","bj");

        //取值
        String age = (String) hashOperations.get("002", "age");
        System.out.println(age);

        //获得hash结构中的所有字段
        Set keys = hashOperations.keys("002");
        for (Object key : keys) {
            System.out.println(key);
        }

        //获得hash结构中的所有值
        List values = hashOperations.values("002");
        for (Object value : values) {
            System.out.println(value);
        }
    }

    /**
     * 操作List类型的数据
     */
    @Test
    public void testList(){
        ListOperations listOperations = redisTemplate.opsForList();

        //存值
        listOperations.leftPush("mylist","a");
        listOperations.leftPushAll("mylist","b","c","d");

        //取值
        List<String> mylist = listOperations.range("mylist", 0, -1);
        for (String value : mylist) {
            System.out.println(value);
        }

        //获得列表长度 llen
        Long size = listOperations.size("mylist");
        int lSize = size.intValue();
        for (int i = 0; i < lSize; i++) {
            //出队列
            String element = (String) listOperations.rightPop("mylist");
            System.out.println(element);
        }
    }

    /**
     * 操作Set类型的数据
     */
    @Test
    public void testSet(){
        SetOperations setOperations = redisTemplate.opsForSet();

        //存值
        setOperations.add("myset","a","b","c","a");

        //取值
        Set<String> myset = setOperations.members("myset");
        for (String o : myset) {
            System.out.println(o);
        }

        //删除成员
        setOperations.remove("myset","a","b");

        //取值
        myset = setOperations.members("myset");
        for (String o : myset) {
            System.out.println(o);
        }

    }

    /**
     * 操作ZSet类型的数据
     */
    @Test
    public void testZset(){
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();

        //存值
        zSetOperations.add("myZset","a",10.0);
        zSetOperations.add("myZset","b",11.0);
        zSetOperations.add("myZset","c",12.0);
        zSetOperations.add("myZset","a",13.0);

        //取值
        Set<String> myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }

        //修改分数
        zSetOperations.incrementScore("myZset","b",20.0);

        //取值
        myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }

        //删除成员
        zSetOperations.remove("myZset","a","b");

        //取值
        myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }
    }

    /**
     * 通用操作,针对不同的数据类型都可以操作
     */
    @Test
    public void testCommon(){
        //获取Redis中所有的key
        Set<String> keys = redisTemplate.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }

        //判断某个key是否存在
        Boolean itcast = redisTemplate.hasKey("itcast");
        System.out.println(itcast);

        //删除指定key
        redisTemplate.delete("myZset");

        //获取指定key对应的value的数据类型
        DataType dataType = redisTemplate.type("myset");
        System.out.println(dataType.name());

    }
}
RedisConfig
package com.itheima.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类
 */

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        //默认的Key序列化器为:JdkSerializationRedisSerializer
//设置新的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }

}

Guess you like

Origin blog.csdn.net/weixin_55008454/article/details/130191830