pom.xml引入依赖包
<!--jedis.jar --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- Spring下使用Redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.1.3.RELEASE</version> </dependency>
其余的依赖包就不贴出来了
java配置目录结构
WebAppInitializer.java
/* * Spring Mvc的配置 *createDate: 2018年12月21日 * author: dz * */ public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { private final static Logger LOG = Logger.getLogger(String.valueOf(WebAppInitializer.class)); @Override protected Class<?>[] getRootConfigClasses() { LOG.info("root配置类初始化"); return new Class<?>[]{RootConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { LOG.info("------web配置类初始化------"); return new Class<?>[]{WebConfig.class}; } @Override protected String[] getServletMappings() { LOG.info("------映射根路径初始化------"); return new String[]{"/"};//请求路径映射,根路径 } @Override protected Filter[] getServletFilters() { LOG.info("-----编码过滤配置-------"); CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter("UTF-8"); return new Filter[]{encodingFilter}; } }
RootConfig.java
/** * <p>Title: RootConfig.java</p> * <p>Description: 配置类,用于管理ContextLoadListener创建的上下文的bean</p> * <p>CreateDate: 2018年12月20日</p> * * @author dz */ @Configuration @ComponentScan(basePackages = {"com.dznfit.service"}) @PropertySource("classpath:jdbc.properties") @PropertySource("classpath:redis.properties") @Import({MybatisConfig.class, ShiroConfig.class, RedisConfig.class}) public class RootConfig { @Bean public static PropertySourcesPlaceholderConfigurer sourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
WebConfig.java
/** * <p>Title: WebConfig.java</p> * <p>Description: 配置类,用于定义DispatcherServlet上下文的bean</p> * <p>CreateDate: 2018年12月20日</p> * * @author dz */ @Configuration @EnableWebMvc @EnableAspectJAutoProxy @ComponentScan(basePackages = "com.dznfit.controller") @ComponentScan(basePackages = "com.dznfit.cache") public class WebConfig implements WebMvcConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/view/", ".jsp"); } @Bean public CustomExceptionResolver getExceptionResolver(){ return new CustomExceptionResolver(); } }
MybatisConfig.java
/** * <p>Title: DruidDataSourceConfig.java</p> * <p>Description: 数据源属性配置</p> * <p>CreateDate: 2018年12月20日</p> * * @author dz */ @Configuration @MapperScan(basePackages = "com.dznfit.dao") @EnableTransactionManagement public class MybatisConfig { @Value("${driver}") private String driver; @Value("${url}") private String url; @Value("${name}") private String user; @Value("${password}") private String password; @Autowired private Environment environment; @Bean("dataSource") public DataSource dataSourceConfig() throws PropertyVetoException { // 使用c3p0 ComboPooledDataSource source = new ComboPooledDataSource(); source.setDriverClass(driver); source.setJdbcUrl(url); source.setUser(user); source.setPassword(password); return source; } @Bean("sqlSessionFactoryBean") public SqlSessionFactoryBean sqlSessionFactoryBeanConfig() throws PropertyVetoException, IOException { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(this.dataSourceConfig()); factoryBean.setTypeAliasesPackage("com.dznfit.entity"); factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml")); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factoryBean.setMapperLocations(resolver.getResources("Mapper/*.xml")); return factoryBean; } /* <!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 -->*/ @Bean("transactionManager") public DataSourceTransactionManager dataSourceTransactionManagerConfig() throws PropertyVetoException { DataSourceTransactionManager manager = new DataSourceTransactionManager(); manager.setDataSource(this.dataSourceConfig()); return manager; } }
RedisConfig.java
注意必须是java1.8以上才可以编译通过
@Configuration @EnableCaching public class RedisConfig { @Bean RedisConnectionFactory redisFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); return new JedisConnectionFactory(config); } @Bean RedisTemplate redisTemplate() { StringRedisTemplate template = new StringRedisTemplate(redisFactory()); template.setValueSerializer(RedisSerializer.json()); return template; } @Bean RedisCacheManager cacheManager() { RedisCacheConfiguration with = RedisCacheConfiguration .defaultCacheConfig() .computePrefixWith(cacheName -> "dz147." + cacheName) .serializeKeysWith(RedisSerializationContext.SerializationPair. fromSerializer(RedisSerializer.string())) .serializeValuesWith(RedisSerializationContext.SerializationPair. fromSerializer(RedisSerializer.json())); return RedisCacheManager.builder(redisFactory()).cacheDefaults(with).build(); } }
使用就非常简单了
Controller部分
@GetMapping(value = "/redis/{id}") //@GetCache(name="news",value="id") public @ResponseBody News redisTest(@PathVariable("id")int id) { return newsService.getNewsById(id); }
Service部分
我们只需要加上@Cacheable注解即可
@Service public class NewsServiceImpl { @Autowired NewsMapper newsMapper; @Cacheable("news") public News getNewsById(int id) { return newsMapper.selectByPrimaryKey(id); } }
Test部分
@RunWith(SpringRunner.class) @ContextConfiguration(classes = RootConfig.class) public class NewsServiceImplTest { @Autowired NewsServiceImpl newsService; @Test public void getNewsById() { newsService.getNewsById(2); } }