Springboot整合mybatis并配置redis缓存
博客专区 > viakiba 的博客 > 博客详情
Springboot整合mybatis并配置redis缓存
viakiba 发表于5个月前
Springboot整合mybatis并配置redis缓存
  • 发表于 5个月前
  • 阅读 32
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

摘要: 不完全指南

代码位置:

https://github.com/viakiba/springboot/tree/master/springbootredis

引入依赖查看pom文件不再贴出来。

首先,配置application.properties

#server.port = 8080
spring.debug = true
# DATASOURCE
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot
spring.datasource.username = root
spring.datasource.password = 951357qaz
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource

# mybatis
mybatis.configLocation: classpath:mybatis-config.xml

# REDIS (RedisProperties)  
spring.redis.host=127.0.0.1 
spring.redis.port=6379

#thymeleaf
spring.thymeleaf.suffix=.html  
spring.thymeleaf.content-type=text/html
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.mode=HTML5
# ;charset=<encoding> is added
#spring.thymeleaf.encoding=UTF-8
# set to false for hot refresh
spring.thymeleaf.cache=false

然后设置mybatis配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <settings>
    <setting name="logImpl" value="LOG4J"/>
  </settings>
</configuration>

最后设置logback:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<!-- 引用顶级配置 -->
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <!-- 属性: 
            1)name:用来指定受此logger约束的某一个包或者具体的某一个类 
            2)level:用来设置打印级别,大小写无关(最常用的几种):DEBUG, INFO, WARN, ERROR 
    -->
    <!-- 这一句至关重要如果没有,就无法输出sql语句 -->
    <logger name="com.example.demo.dao" level="DEBUG"></logger>
 </configuration>

配置文件配置完毕,代码方面:

第一个设置key的生成原则,在config包下:

package com.example.demo.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCacheManager;  
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method; 
@Configuration  
@EnableCaching  
public class CacheRedisConfig extends CachingConfigurerSupport{  
  
	@Autowired
    private JedisConnectionFactory jedisConnectionFactory;
	
	@Bean(name = "SimpleKey")
	public KeyGenerator getKeyGenerator(){
		return new KeyGenerator() {  
          @Override  
          public Object generate(Object target, Method method, Object... params) {  
              StringBuilder sb = new StringBuilder();  
              sb.append(target.getClass().getName());  
              sb.append(method.getName());  
              for (Object obj : params) {  
                  sb.append(obj.toString());  
              }
              System.out.println(sb.toString());
              return sb.toString();  
          }  
      }; 
	}
    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
        return redisCacheManager;
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
       
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        // 开启事务支持
        redisTemplate.setEnableTransactionSupport(true);
        // 使用String格式序列化缓存键
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        
        redisTemplate.setValueSerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
        
        return redisTemplate;
    } 
}  

设置数据库连接池,也是在config包下:

package com.example.demo.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/** 
 * @description: 
 * @author viakiba
 * @date 2017年7月12日
 */
@Configuration
@MapperScan(basePackages = DruidDataSourceConfig.PACKAGE,sqlSessionFactoryRef = "sqlSessionFactory")
public class DruidDataSourceConfig {
	static final String PACKAGE = "com.example.demo.dao";
	static final String MAPPER_LOCATION = "classpath:mapper/*.xml";
	
	//接下来使用的value注解获取application.properties拿到值进行初始化  spring-EL表达式
	@Value("${spring.datasource.url}")
	private String url ;
	@Value("${spring.datasource.username}")
	private String user ;
	@Value("${spring.datasource.password}")
	private String password ;
	@Value("${spring.datasource.driver-class-name}")
	private String driverClass ;
	
	//数据源
	//Bean明确地指示产生一个bean的方法,并且交给Spring容器管理;
	@Bean(name="dataSource")
	//标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。「多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean
	@Primary
	public DataSource dataSource(){
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setUrl(url);
		druidDataSource.setUsername(user);
		druidDataSource.setPassword(password);
		druidDataSource.setDriverClassName(driverClass);
		return druidDataSource;
		
	}
	//主库事务
	@Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
	//主库sqlSessionFactory   @Qualifier("XXX") 中的 XX是 Bean 的名称,所以 @Autowired 和 @Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了。
	@Bean(name = "sqlSessionFactory")
	@Primary
	public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception{
		final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(DruidDataSourceConfig.MAPPER_LOCATION));
		return sqlSessionFactoryBean.getObject();
	}
}

其中的注解作用,不在详细解释。

然后,在dao包下,如下写法:

package com.example.demo.dao;

import org.springframework.cache.annotation.Cacheable;

/** 
 * @description: 
 * @author viakiba
 * @date 2017年7月13日
 */

public interface UserinfoDao {
	
	@Cacheable(value = "usercache",keyGenerator="SimpleKey")  
	public String selectUser();
}

注意simplekey就是config包下,CacheRedisConfig 里面通过@Bean指定名字载入的。

其他关于mybatis的mapper查看application.properties即可。

共有 人打赏支持
粉丝 4
博文 103
码字总数 57660
×
viakiba
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: