pom.xml引入依赖包
redis.clients
jedis
2.9.0
org.springframework.data
spring-data-redis
2.1.3.RELEASE
其余的依赖包就不贴出来了
java配置目录结构
WebAppInitializer.java
/** Spring Mvc的配置
*createDate: 2018年12月21日
* author: dz
**/
public class WebAppInitializer extendsAbstractAnnotationConfigDispatcherServletInitializer {private final static Logger LOG = Logger.getLogger(String.valueOf(WebAppInitializer.class));
@Overrideprotected Class>[] getRootConfigClasses() {
LOG.info("root配置类初始化");return new Class>[]{RootConfig.class};
}
@Overrideprotected Class>[] getServletConfigClasses() {
LOG.info("------web配置类初始化------");return new Class>[]{WebConfig.class};
}
@OverrideprotectedString[] getServletMappings() {
LOG.info("------映射根路径初始化------");return new String[]{"/"};//请求路径映射,根路径
}
@OverrideprotectedFilter[] getServletFilters() {
LOG.info("-----编码过滤配置-------");
CharacterEncodingFilter encodingFilter= new CharacterEncodingFilter("UTF-8");return newFilter[]{encodingFilter};
}
}
RootConfig.java
/***
Title: RootConfig.java
*
Description: 配置类,用于管理ContextLoadListener创建的上下文的bean
*
CreateDate: 2018年12月20日
*
*@authordz*/@Configuration
@ComponentScan(basePackages= {"com.dznfit.service"})
@PropertySource("classpath:jdbc.properties")
@PropertySource("classpath:redis.properties")
@Import({MybatisConfig.class, ShiroConfig.class, RedisConfig.class})public classRootConfig {
@Beanpublic staticPropertySourcesPlaceholderConfigurer sourcesPlaceholderConfigurer() {return newPropertySourcesPlaceholderConfigurer();
}
}
WebConfig.java
/***
Title: WebConfig.java
*
Description: 配置类,用于定义DispatcherServlet上下文的bean
*
CreateDate: 2018年12月20日
*
*@authordz*/@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@ComponentScan(basePackages= "com.dznfit.controller")
@ComponentScan(basePackages= "com.dznfit.cache")public class WebConfig implementsWebMvcConfigurer {
@Overridepublic voidconfigureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/view/", ".jsp");
}
@BeanpublicCustomExceptionResolver getExceptionResolver(){return newCustomExceptionResolver();
}
}
MybatisConfig.java
/***
Title: DruidDataSourceConfig.java
*
Description: 数据源属性配置
*
CreateDate: 2018年12月20日
*
*@authordz*/@Configuration
@MapperScan(basePackages= "com.dznfit.dao")
@EnableTransactionManagementpublic classMybatisConfig {
@Value("${driver}")privateString driver;
@Value("${url}")privateString url;
@Value("${name}")privateString user;
@Value("${password}")privateString password;
@AutowiredprivateEnvironment environment;
@Bean("dataSource")public DataSource dataSourceConfig() throwsPropertyVetoException {//使用c3p0
ComboPooledDataSource source = newComboPooledDataSource();
source.setDriverClass(driver);
source.setJdbcUrl(url);
source.setUser(user);
source.setPassword(password);returnsource;
}
@Bean("sqlSessionFactoryBean")public SqlSessionFactoryBean sqlSessionFactoryBeanConfig() throwsPropertyVetoException, IOException {
SqlSessionFactoryBean factoryBean= newSqlSessionFactoryBean();
factoryBean.setDataSource(this.dataSourceConfig());
factoryBean.setTypeAliasesPackage("com.dznfit.entity");
factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
PathMatchingResourcePatternResolver resolver= newPathMatchingResourcePatternResolver();
factoryBean.setMapperLocations(resolver.getResources("Mapper/*.xml"));returnfactoryBean;
}/**/@Bean("transactionManager")public DataSourceTransactionManager dataSourceTransactionManagerConfig() throwsPropertyVetoException {
DataSourceTransactionManager manager= newDataSourceTransactionManager();
manager.setDataSource(this.dataSourceConfig());returnmanager;
}
}
RedisConfig.java
注意必须是java1.8以上才可以编译通过
@Configuration
@EnableCachingpublic classRedisConfig {
@Bean
RedisConnectionFactory redisFactory() {
RedisStandaloneConfiguration config= newRedisStandaloneConfiguration();return newJedisConnectionFactory(config);
}
@Bean
RedisTemplate redisTemplate() {
StringRedisTemplate template= newStringRedisTemplate(redisFactory());
template.setValueSerializer(RedisSerializer.json());returntemplate;
}
@Bean
RedisCacheManager cacheManager() {
RedisCacheConfiguration with=RedisCacheConfiguration
.defaultCacheConfig()
.computePrefixWith(cacheName-> "dz147." +cacheName)
.serializeKeysWith(RedisSerializationContext.SerializationPair.
fromSerializer(RedisSerializer.string()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.
fromSerializer(RedisSerializer.json()));returnRedisCacheManager.builder(redisFactory()).cacheDefaults(with).build();
}
}
使用就非常简单了
Controller部分
@GetMapping(value = "/redis/{id}")//@GetCache(name="news",value="id")
public @ResponseBody News redisTest(@PathVariable("id")intid) {returnnewsService.getNewsById(id);
}
Service部分
我们只需要加上@Cacheable注解即可
@Servicepublic classNewsServiceImpl {
@Autowired
NewsMapper newsMapper;
@Cacheable("news")public News getNewsById(intid) {returnnewsMapper.selectByPrimaryKey(id);
}
}
Test部分
@RunWith(SpringRunner.class)
@ContextConfiguration(classes= RootConfig.class)public classNewsServiceImplTest {
@Autowired
NewsServiceImpl newsService;
@Testpublic voidgetNewsById() {
newsService.getNewsById(2);
}
}