Spring缓存机制整合Redis实例(全注解方式)

jar包准备:mybatis3.4.1+mybatis-spring1.3.1+spring4.3.2+redis+mysql-conncetor+dbcp+log4j+Junit

Spring缓存机制整合Redis实例(全注解方式)_第1张图片

结构:

Spring缓存机制整合Redis实例(全注解方式)_第2张图片

package me.pojo;

import java.io.Serializable;

public class Role implements Serializable{
	private static final long serialVersionUID = 1L;
	private Long id;
	private String roleName;
	private String note;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getRoleName() {
		return roleName;
	}
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}
	public String getNote() {
		return note;
	}
	public void setNote(String note) {
		this.note = note;
	}
	
}
package me.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import me.pojo.Role;
@Repository//通过扫描和注解联合定义dao层
public interface RoleDao {
	public Role getRole(Long id);
	public int deleteRole(Long id);
	public int insertRole(Role role);
	public int updateRole(Role role);
	public List findRoles(@Param("roleName") String roleName,@Param("note") String note);
}



	
	
		delete from t_role where id=#{id}
	
	
		insert into t_role (role_name,note) values(#{roleName},#{note})
	
	
		update t_role set role_name=#{roleName},note=#{note} where id=#{id}
	
	
package me.service;

import java.util.List;

import me.pojo.Role;

public interface RoleService {
	public Role getRole(Long id);
	public int deleteRole(Long id);
	public Role insertRole(Role role);
	public Role updateRole(Role role);
	public List findRoles(String roleName,String note);
}
package me.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import me.dao.RoleDao;
import me.pojo.Role;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao=null;
	
	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
	@Cacheable(value = "redisCacheManager",key = "'redis_role_'+#id")
	public Role getRole(Long id) {
		return roleDao.getRole(id);
	}

	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
	@CacheEvict(value = "redisCacheManager",key = "'redis_role_'+#id")
	public int deleteRole(Long id) {
		return roleDao.deleteRole(id);
	}

	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
	@CachePut(value = "redisCacheManager",key = "'redis_role_'+#result.id")
	public Role insertRole(Role role) {
		roleDao.insertRole(role);
		return role;
	}

	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
	@CachePut(value = "redisCacheManager",key = "'redis_role_'+#role.id")
	public Role updateRole(Role role) {
		roleDao.updateRole(role);
		return role;
	}

	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
	public List findRoles(String roleName, String note) {
		return roleDao.findRoles(roleName, note);
	}

}
package me.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

@Configuration
@ComponentScan("me.*")//定义spring扫描的包
@EnableTransactionManagement//使用事务驱动管理器
//实现接口配置注解驱动事务
public class RootConfig implements TransactionManagementConfigurer {

	private DataSource dataSource=null;
	/**
	 * 配置数据库
	 * @return数据连接池
	 */
	@Bean(name="dataSource")
	public DataSource initDataSource() {
		if(dataSource!=null) {
			return dataSource;
		}
		Properties props=new Properties();
		props.setProperty("driverClassName", "com.mysql.jdbc.Driver");
		props.setProperty("url", "jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8&useSSL=true");
		props.setProperty("username", "root");
		props.setProperty("password", "xxxxxx");
		try {
			dataSource=BasicDataSourceFactory.createDataSource(props);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return dataSource;
	}
	/**
	 * 配置sqlSessionFactory
	 * @return sqlSessionFactory
	 */
	@Bean(name="sqlSessionFactory")
	public SqlSessionFactoryBean initSqlSessionFactory() {
		SqlSessionFactoryBean sqlSessionFactory=new SqlSessionFactoryBean();
		//数据库
		sqlSessionFactory.setDataSource(initDataSource());
		//配置Mybatis配置文件
		Resource resource=new ClassPathResource("mybatis.xml");
		sqlSessionFactory.setConfigLocation(resource);
		return sqlSessionFactory;
	}
	/**
	 * 通过自动扫描发现mapper接口
	 * @return
	 */
	@Bean
	public MapperScannerConfigurer initMapperScannerConfigurer() {
		MapperScannerConfigurer msc=new MapperScannerConfigurer();
		//扫描包
		msc.setBasePackage("me.*");
		msc.setSqlSessionFactoryBeanName("sqlSessionFactory");
		//区分注解扫描
		msc.setAnnotationClass(Repository.class);
		return msc;
	}
	/**
	 * 注册注解事务,当@Transactional使用的时候产生数据库事务
	 */
	@Override
	@Bean(name="annotationDrivenTransactionManager")
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();
		transactionManager.setDataSource(initDataSource());
		return transactionManager;
	}

}
package me.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching//启动缓存机制
public class RedisConfig {
	@Bean(name="redisTemplate")
	public RedisTemplate initRedisTemplate() {
		JedisPoolConfig poolConfig=new JedisPoolConfig();
		//最大空闲数
		poolConfig.setMaxIdle(50);
		//最大连接数
		poolConfig.setMaxTotal(100);
		//最大等待毫秒数
		poolConfig.setMaxWaitMillis(20000);
		//创建Jedis连接工厂
		JedisConnectionFactory connectionFactory=new JedisConnectionFactory(poolConfig);
		connectionFactory.setHostName("127.0.0.1");
		connectionFactory.setPort(6379);
		//调用后初始化方法,没有它将抛出异常
		connectionFactory.afterPropertiesSet();
		//自定义Redis序列化器
		RedisSerializer jdkSerializationRedisSerializer=new JdkSerializationRedisSerializer();
		RedisSerializer stringRedisSerializer=new StringRedisSerializer();
		//定义RedisTemple,并设置连接工厂
		RedisTemplate redisTemplate=new RedisTemplate<>();
		redisTemplate.setConnectionFactory(connectionFactory);
		//设置序列化器
		redisTemplate.setDefaultSerializer(stringRedisSerializer);
		redisTemplate.setKeySerializer(stringRedisSerializer);
		redisTemplate.setValueSerializer(jdkSerializationRedisSerializer);
		redisTemplate.setHashKeySerializer(stringRedisSerializer);
		redisTemplate.setHashValueSerializer(jdkSerializationRedisSerializer);
		return redisTemplate;
	}
	
	/**
	 * 
	 * @param redisTemplate
	 * @return
	 */
	@Bean(name="redisCacheManager")
	public CacheManager initRedisCacheManager(@Autowired RedisTemplate redisTemplate) {
		RedisCacheManager cacheManager=new RedisCacheManager(redisTemplate);
		cacheManager.setDefaultExpiration(600);
		List cacheNames=new ArrayList<>();
		cacheNames.add("redisCacheManager");
		cacheManager.setCacheNames(cacheNames);
		return cacheManager;
	}
}






# Global logging configuration
log4j.rootLogger=debug, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

//测试:

package test;

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import me.config.RedisConfig;
import me.config.RootConfig;
import me.pojo.Role;
import me.service.RoleService;

class RoleDaoTest {

	@Test
	void testInsert() {
		ApplicationContext cxt=new AnnotationConfigApplicationContext(RootConfig.class,RedisConfig.class);
		RoleService rs=cxt.getBean(RoleService.class);
		Role role=new Role();
		role.setNote("0908");
		role.setRoleName("很幸福1");
		rs.insertRole(role);
		Role getRole=rs.getRole(role.getId());
		System.out.println(getRole.getNote());
		getRole.setNote("新的1");
		System.out.println(rs.updateRole(getRole));
	}

}




//结果:

Spring缓存机制整合Redis实例(全注解方式)_第3张图片

Spring缓存机制整合Redis实例(全注解方式)_第4张图片

 

你可能感兴趣的:(spring缓存,Redis,JavaWeb基础及常用框架)