springboot+mybatis+redis框架搭建

前言:

        本人实际开发中没用到过springboot框架,但因为最近springboot实在是太火了,然后就自己搭建了一套,当然,参考了许多优秀的coder写的博客,不过大多数都是零碎的,所以就想写一套完整的框架搭建流程。

开发工具:eclipse

搭建前准备工作:

        1.java环境(不多说)

        2.本地maven配置安装(网上很多教程)

        3.redis配置安装(很简单,官网下个压缩包解压即可)

当你上面的所有准备都OK了,那么恭喜你,接下来你会特别的顺利。

1。搭建springboot工框架

                a.打开elipse,邮件NEW--》project--》Maven Project,然后一直下一步

                    springboot+mybatis+redis框架搭建_第1张图片

    b.输入Group Id以及Artifact Id,两个可以一样,我直接用的项目名,然后finish即可,到这里,你的maven项目创建成功

                    springboot+mybatis+redis框架搭建_第2张图片

c.当然啦,我们现在开发一般都是基于web项目,所以我这里讲项目转换成了web项目。具体操作流程为:点击项目,右键,在弹出框选择Configure,选择convert to faceted form,弹出框勾选Dynamic Web Modual即可。

                    springboot+mybatis+redis框架搭建_第3张图片

d.这里为止,一个基于maven的web项目构建好了,然后我们这边开始添加springboot所依赖的jar。在pom.xml文件中加入如下配置,如下图,这样springboot基本包算是添加完了(很简单吧)

            springboot+mybatis+redis框架搭建_第4张图片

    


	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.7.RELEASE
		 
	

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

e.编写代码,在编写代码之前我这里要强调一下的是,spring-boot项目有严格的层级要求,所以在编码前,最好是先把要建的文件夹给建好。我这里顺序是这样的,在src/main下面建三个文件夹,分别是java(主要是写代码的地方),resources(主要是配置文件的地方),webapp(主要是装页面的地方),我这里先写个Controller,同传统spring一样,然后再controller包同级的地方写个启动类Start。启动main方法,在浏览器输入:localhost:8080/home,到此,springboot框架就搭建好了。

注意:为什么要在controller包同级的地方写个启动类Start,这是为了然Start处于最外层,这样他能够读取到Controller里面所有的配置文件,当然啦,你也可以在com.cn.controller下面去屑启动方法,不过这样不利于后面测试,因为你每写一个controller都需要改start方法

代码结构如下:

                                

                        springboot+mybatis+redis框架搭建_第5张图片

HomeController代码:   

package com.cn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HomeController {

	@RequestMapping("/home")
	@ResponseBody
	public String getHome() {

		return "hello,spring-boot!!!";
	}
	
}

Start代码:

package com.cn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Start {

	public static void main(String[] args) {
        SpringApplication.run(Start.class, args);
    }
	
}
springboot+mybatis+redis框架搭建_第6张图片

        

2.集成mybatis(这一块同以前的spring框架集成类似)

    a.因为我本地用的是mysql,所以在pom文件我加的是mysql的驱动jar,同时加入mybatis依赖的jar


		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.1.1
		

		
		
			mysql
			mysql-connector-java
		

b.在resources文件夹下面创建applicaiton.properties,然后将数据源写入文件

###############数据库mybaties配置###############
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.cn.entity
  
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = kangbiao1234

c.编码,在编码之前,同样是先建好文件夹,大家可以仿照我这边的目录结构,然后写入相应的java文件以及xml文件。当然啦,大家得先建立好数据库

springboot+mybatis+redis框架搭建_第7张图片

User:

package com.cn.entity;

import java.io.Serializable;
import java.util.List;

public class User implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public String id;
	public int age;
	public String name;
	public List userlist;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List getUserlist() {
		return userlist;
	}

	public void setUserlist(List userlist) {
		this.userlist = userlist;
	}

}

UserMapper.java:

package com.cn.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.cn.entity.User;

@Mapper
public interface UserMapper {

	List getAll();

	User getOne(Integer id);

	void insert(User user);

	void update(User user);

	void delete(Integer id);

}
userMapper.xml
  


	
		
		
		
	

	
		id, name, age
	

	

	

	
		INSERT INTO
		user
		(id,name,age)
		VALUES
		(#{id},#{name}, #{age})
	

	
		UPDATE
		user
		SET
		name = #{name},
		age = #{age},
		WHERE
		id = #{id}
	

	
		DELETE FROM
		user
		WHERE
		id =#{id}
	

  

mybatis-config.xml:

  


	
	
		
		

		
		
		
		
		

		
		
		
		

		
		

		
		

		
		
		
		

		
		

		

		

	

	
		
		
		
		
		
		
	
  

d.在HomeController.java这个文件里加上如下代码即可。到此,springboot+mybatis框架搭建完成

@Autowired
	private UserMapper userMapper;

	@RequestMapping("/getUsers")
	public String getUsers(Model model) {
		List users = userMapper.getAll();
		model.addAttribute("users", users);
		return "user/userList";
	}

3.集成redis

    a.在pom文件里面引入redis相关jar


		
			org.springframework.boot
			spring-boot-starter-data-redis
		
		
			redis.clients
			jedis
			2.8.0
		
		
		
			org.mybatis
			mybatis-ehcache
			1.0.0
		

b.接下来在application.properties文件里面加入redis的配置

#redis
#redis数据库名称  从0到15,默认为db0
spring.redis.database=0
#redis服务器名称
spring.redis.host=127.0.0.1
#redis服务器密码
spring.redis.password=
#redis服务器连接端口号
spring.redis.port=6379
#redis连接池设置
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.maxTotal=8
spring.redis.pool.maxWaitMillis=1000
#spring.redis.sentinel.master=
#spring.redis.sentinel.nodes=
spring.redis.timeout=60000

c.创建缓存实现类以及中间类

                    springboot+mybatis+redis框架搭建_第8张图片

MybatisRedisCache:

package com.cn.redis;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import com.cn.controler.HomeController;

import redis.clients.jedis.exceptions.JedisConnectionException;

public class MybatisRedisCache implements Cache {

	private static JedisConnectionFactory jedisConnectionFactory;
	private final static Logger logger = LoggerFactory.getLogger(HomeController.class);

    private final String id;

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public MybatisRedisCache(final String id) {
    	logger.info("====================MybatisRedisCache=====================");
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    @Override
    public void clear() {
    	logger.info("====================clear=====================");
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            connection.flushDb();
            connection.flushAll();
        } catch (JedisConnectionException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public String getId() {
    	logger.info("====================getId=====================");
        return this.id;
    }

    @Override
    public Object getObject(Object key) {
    	logger.info("====================getObject=====================");
        Object result = null;
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            result = serializer.deserialize(connection.get(serializer.serialize(key)));
        } catch (JedisConnectionException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

    @Override
    public int getSize() {
    	logger.info("====================getSize=====================");
        int result = 0;
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            result = Integer.valueOf(connection.dbSize().toString());
        } catch (JedisConnectionException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    @Override
    public void putObject(Object key, Object value) {
    	logger.info("====================putObject=====================");
        RedisConnection connection = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
        } catch (JedisConnectionException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public Object removeObject(Object key) {
    	logger.info("====================removeObject=====================");
        RedisConnection connection = null;
        Object result = null;
        try {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            result = connection.expire(serializer.serialize(key), 0);
        } catch (JedisConnectionException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        MybatisRedisCache.jedisConnectionFactory = jedisConnectionFactory;
    }

} 
  

RedisCacheTransfer:

package com.cn.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;

@Component
public class RedisCacheTransfer {
	@Autowired
	public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
		MybatisRedisCache.setJedisConnectionFactory(jedisConnectionFactory);
	}
}

d:创建redis数据源applicationContext-cache.xml

                springboot+mybatis+redis框架搭建_第9张图片

applicationContext-cache.xml:



	
	
	
	






	

e.在userMpper.xml文件里面加入Mybatis二级缓存

    这里的路径就是刚刚编写的缓存实现类

        springboot+mybatis+redis框架搭建_第10张图片

f.到此,springboot+mybatis+redis的框架搭建完成

拓展:引入日志

因为springboot的jar已经引入了loggin的jar,所以这里不需要加入其它日志的jar,在resources下创建logback-spring.xml,然后再application.properties里面引入路径

logback-spring.xml:



    
     
    
    
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
        
    
    
    
        
            
            ${LOG_HOME}/log.log.%d{yyyy-MM-dd}.log
            
            30
        
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
        
        
        
            10MB
        
    

    
    

    
    
        
        
    
    
    
        
        
            
            
                
                
                
                
            
        
    

application.properties加入如下配置

#日志配置路径
logging.config=classpath:logback-spring.xml
#打印sql语句
logging.level.com.cn.mapper=DEBUG

欢迎大家进群交流

QQ群:719431817

你可能感兴趣的:(框架)