springboot+mybatis+redis+linux(mysql,tomcat)实现简单增删改查

 

 

springboot整合mybatis:https://blog.csdn.net/qq_36516464/article/details/79780621

ubuntu16.0安装MySQL(使用root账户,sudo -i 切换root账号):

1 sudo apt-get install mysql-server

2 sudo apt-get install mysql-cli

3 sudo apt-get install libmysqlclient-dev

安装过程中会提示设置密码,安装完成后可使用以下命令查询是否安装成功

sudo netstat -tap | grep mysql

可使用以下命令登陆MySQL

# -u表示要登陆的账号,-p 表示登入MySQL的密码,回车之后输入正确的密码就可以进入MySQL
mysql -u root -p

ps:安装过程可能会报: Installing MySQL system tables..../bin/mysqld: error while loading shared libraries: libaio.so.1: cannot open shared object file: No such file or directory。 解决方案:sudo apt-get install libaio-dev

开启远程服务需要修改mysql.conf文件,将里面的bind-address 注释掉或改成0.0.0.0,使用以下命令可进入修改界面

vi /etc/mysql/mysql.conf.d/mysqld.cnf

建议在最底部加入 skip-name-resolve,不加的话使用Navicat连接远程数据库反应会很慢。

 

1.登陆MySQL设置远程登陆账号

#第一个admin表示用户名,%表示所有的电脑都可以连接,也可以设置某个ip地址运行连接,第二个123表示密码
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY '123' WITH GRANT OPTION;

2.执行立即生效

flush privileges;

3.查询远程连接账号是否创建成功

SELECT DISTINCT CONCAT('User: ''',user,'''@''',host,''';') AS query FROM mysql.user;

 

至此MySQL的远程服务开启成功,使用exit;命令退出MySQL。

#关闭MySQL命令
service mysql stop

#启动MySQL命令
service mysql start

#查询MySQL状态
ps -ef|grep mysql

#查询Linux IP地址
ifconfig

使用Navicat测试连接

连接成功。

 

安装Redis

#安装redis服务
sudo apt-get install redis-server

#启动redis
redis-cli

#检测是否启动成功,出现PONG启动成功
ping

接下开启远程连接需要修改redis的配置文件,进入配置文件命令

#进入reids配置文件
vi /etc/redis/redis.conf

将bind-address=127.0.0.1注释掉

 

查看redis是否支持远程连接

#查看redis状态
ps -aux|grep redis

#显示redis-server*:6379,远程开启成功,需要让指定的ip地址连接只需将bind-address=改为需要连接的IP地址即可
redis       974  0.1  0.2  47204  2584 ?        Ssl  14:51   0:33 /usr/bin/redis-server *:6379
root      67890  0.0  0.1  15988  1056 pts/1    S+   21:43   0:00 grep --color=auto redis

安装Tomcat之前需要安装jdk,我安装的版本是jdk-8u181-linux-x64.tar.gz,去官网下载下载Linux版本的jdk即可

1.在/usr/lib/中新建一个java的文件夹用于存放jdk

#复制gz到指定的文件夹
cp jdk-8u181-linux-x64.tar.gz /usr/lib/java

2.解压gz压缩包

#解压gz压缩包(需将在你CP到的文件夹中执行命令)
tar -zxvf jdk-8u181-linux-x64.tar.gz

3.配置环境变量

#配置环境变量
vi /etc/profile


#将一下代码粘贴到头部即可
export JAVA_HOME=/usr/lib/java/jdk1.8.0_181  #jdk解压的文件目录,对应你的jdk版本即可
export JRE_HOME=$JAVA_HOME/jre
export CLASSPATH=.:$JAVA_HOME/lib:$JRE_HOME/lib:$CLASSPATH
export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH


退出编辑后执行以下命令

source  /etc/profile

测试jdk是否安装成功

#测试jdk
java -version

#安装成功输入
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

至此我们所需要的环境都已经配置好了,现在来看代码。

application.properties文件

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc\:mysql\://192.168.1.131\:3306/mytest
spring.datasource.username=admin
spring.datasource.password=123
server.port=8080



#mapper映射路径
mybatis.mapper-locations=classpath*:mapper/*.xml

#实体类路径
mybatis.type-aliases-package=con.example.springBoot.entity

#打印日志
logging.level.com.example.springBoot.controller.LinuxTableController=WARN
logging.level.com.example.springBoot.mapper.LinuxTableMapper=DEBUG
logging.file=logs/spring-boot-logging.log


# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
#redis密码,没有设置可以忽略
spring.redis.password=123
# Redis服务器地址
spring.redis.host=192.168.1.131
# Redis服务器连接端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0

spring.profiles=default
spring.freemarker.charset=utf-8
#设定ftl文件路径
spring.freemarker.template-loader-path=classpath:/templates
#设定静态文件路径,js,css等
spring.mvc.static-path-pattern=/static/**
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html; 
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl



 redis工具类

package com.example.springBoot.redisTool;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;

/**
 * Demo class
 *
 * @author zengjinlong
 * @date 2018/7/24
 */
@Configuration
//开启缓存
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));

        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    public class Receiver {


        private CountDownLatch latch;

        @Autowired
        public Receiver(CountDownLatch latch) {
            this.latch = latch;
        }

        public void receiveMessage(String message) {
            latch.countDown();
        }
    }

}

 service

package com.example.springBoot.service;

import com.example.springBoot.entity.LinuxTable;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * Demo class
 *
 * @author zengjinlong
 * @date 2018/7/24
 */
@Service
public interface LinuxTableService {
    List<LinuxTable> findAll();

    LinuxTable findById(LinuxTable uid);

    int addObject(LinuxTable linuxTable);

    int updateObject();

    int deleteObject(LinuxTable linuxTable);

}
package com.example.springBoot.service.Impl;

import com.alibaba.fastjson.JSON;
import com.example.springBoot.entity.LinuxTable;
import com.example.springBoot.mapper.LinuxTableMapper;
import com.example.springBoot.service.LinuxTableService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * Demo class
 *
 * @author zengjinlong
 * @date 2018/7/24
 */
@Service
public class LinuxTableServiceImpl implements LinuxTableService {
    private final  String packages             
    =LinuxTableServiceImpl.class.getPackage().toString();

    @Autowired
    private LinuxTableMapper linuxTableMapper;

    /***
     * 注入redis
     */
    @Autowired
    private StringRedisTemplate template;

    @Override
    public List<LinuxTable> findAll() {
        List<LinuxTable> list = null;
        System.out.println(packages+".findAll");
        //查询key是否存在,存在true反之false
        boolean flag = template.hasKey(packages+".findAll");
        if(!flag){
            list = linuxTableMapper.findAll();
            System.out.println(list);
            //存入redis中,参数(key,value);
            template.opsForValue().set(packages+".findAll",JSON.toJSONString(list));
        }else {
            list = JSON.parseArray(template.opsForValue().get(packages+".findAll"),LinuxTable.class);
            //根据key取出对应的value
            System.out.println(template.opsForValue().get(packages+".findAll"));
        }
        return list;
    }

    @Override
    public LinuxTable findById(LinuxTable uid) {
        LinuxTable linuxTable = null;
        boolean flag = template.hasKey(packages+".findById");
        if(!flag){
            if(uid != null){
                linuxTable = linuxTableMapper.findById(uid);
                String json = JSON.toJSONString(linuxTable);
                template.opsForValue().set(packages+".findById", json);
            }
        }else{
            String json = template.opsForValue().get(packages+".findById");
            linuxTable = JSON.parseObject(json,LinuxTable.class);
        }
        return linuxTable;
    }

    @Override
    public int addObject(LinuxTable linuxTable) {
        List<LinuxTable> list = JSON.parseArray(template.opsForValue().get(packages+".findAll"),LinuxTable.class);
        boolean flag = list.contains(linuxTable);
        if(!flag){
            //不存在
            list.add(linuxTable);
            linuxTableMapper.addObject(linuxTable);
            template.opsForValue().set(packages+".findAll",JSON.toJSONString(list));
        }
        return 1;
    }

    @Override
    public int updateObject() {
        return 0;
    }

    @Override
    public int deleteObject(LinuxTable linuxTable) {
        List<LinuxTable> list = JSON.parseArray(template.opsForValue().get(packages+".findAll"),LinuxTable.class);
        list.remove(linuxTable);
        linuxTableMapper.deleteObject(linuxTable);
        template.opsForValue().set(packages+".findAll",JSON.toJSONString(list));
        return 1;
    }
}

Mapper

package com.example.springBoot.mapper;

import com.example.springBoot.entity.LinuxTable;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
/**
 * Demo class
 *
 * @author zengjinlong
 * @date 2018/7/24
 */
@Mapper
public interface LinuxTableMapper {
    List<LinuxTable> findAll();

    LinuxTable findById(LinuxTable uid);

    int addObject(LinuxTable linuxTable);

    int updateObject();

    int deleteObject(LinuxTable linuxTable);

}

 Controller

package com.example.springBoot.controller;

import com.example.springBoot.entity.LinuxTable;
import com.example.springBoot.service.LinuxTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
/**
 * Demo class
 *
 * @author zengjinlong
 * @date 2018/7/24
 */
@RestController
@RequestMapping("/myController")
public class LinuxTableController {
    @Autowired
    private LinuxTableService linuxTableService;

    @RequestMapping(value = "/findById")
    public LinuxTable finById(){
        LinuxTable table = new LinuxTable();
        table.setUid(2);
        LinuxTable list =  linuxTableService.findById(table);
        return list;
    }

    @RequestMapping(value = "/findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        List<LinuxTable> list = linuxTableService.findAll();
        modelAndView.setViewName("index");
        modelAndView.addObject("list",list);
        return modelAndView;
    }

    @RequestMapping(value = "/addObject")
    public String addObject(){
        LinuxTable linuxTable = new LinuxTable(5,"周瑜",new Date(),4);
        linuxTableService.addObject(linuxTable);
        return "OK";
    }

    @RequestMapping(value = "/deleteObject")
    public String deleteObject(){
        LinuxTable linuxTable = new LinuxTable(5,"周瑜",new Date(),4);
        linuxTableService.deleteObject(linuxTable);
        return "OK";
    }
}

 entity

package com.example.springBoot.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.Objects;

/**
 * Demo class
 *
 * @author zengjinlong
 * @date 2018/7/24
 */
public class LinuxTable{
    private int uid;

    private String uname;

    private Date createTime;

    private int createUserId;

    public LinuxTable() {
    }

    public LinuxTable(int uid, String uname, Date createTime, int createUserId) {
        this.uid = uid;
        this.uname = uname;
        this.createTime = createTime;
        this.createUserId = createUserId;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public int getCreateUserId() {
        return createUserId;
    }

    public void setCreateUserId(int createUserId) {
        this.createUserId = createUserId;
    }



    //重写equals方法,只比较对象内容是否相同,不比较地址,用于list.contains()方法;  
    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        LinuxTable that = (LinuxTable) o;
        return uid == that.uid &&
                createUserId == that.createUserId &&
                Objects.equals(uname, that.uname) ;
    }

    @Override
    public String toString() {
        return "LinuxTable{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", createTime=" + createTime +
                ", createUserId=" + createUserId +
                '}';
    }
}

 Mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.springBoot.mapper.LinuxTableMapper">
        <resultMap id="BaseResultMap" type="com.example.springBoot.entity.LinuxTable">
            <id column="uid" jdbcType="INTEGER" property="uid"/>
            <result column="uname" jdbcType="VARCHAR" property="uname"/>
            <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
            <result column="create_userId" jdbcType="INTEGER" property="createUserId"/>
        </resultMap>
    
        <select id="findById" parameterType="com.example.springBoot.entity.LinuxTable" resultMap="BaseResultMap">
            select * from linuxTable
            where
            1 = 1
            <if test="uid != null and uid !=''">
            and uid = #{uid,jdbcType=INTEGER}
            </if>
            <if test="createTime != null and createTime != ''">
            and create_time = #{createTime,jdbcType=VARCHAR}
            </if>
            <if test="uname != null and uname != ''">
            and uname = #{uname,jdbcType=VARCHAR}
            </if>
            <if test="createUserId != null and createUserId !=''">
            and create_userId = #{createUserId,jdbcType=INTEGER}
            </if>
        </select>
    
        <select id="findAll" resultMap="BaseResultMap">
            select * from linuxTable
        </select>
    
        <insert id="addObject" parameterType="com.example.springBoot.entity.LinuxTable">
            insert into linuxTable values (#{uid},#{uname},#{createTime},#{createUserId})
        </insert>

        <delete id="deleteObject" parameterType="com.example.springBoot.entity.LinuxTable">
            delete from linuxTable where uid = #{uid}
        </delete>
</mapper>

 完整pom文件

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>springBoot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>springBoot</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

		<!--热部署-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>

		<!--war-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
            <version>1.2.7</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
			<version>1.5.9.RELEASE</version>
		</dependency>

	</dependencies>


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


</project>

如何打包成war自行百度吧。Idea生成的war在target目录中的test-classes里面,将它CP出来放入Linux中的Tomcat的webapps目录中即可,启动tomcat,通过http://linux的IP:8080/项目名称/即可访问

 有不对之处大家提出来一起讨论。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值