java搭建redis缓存_java配置SSM框架下的redis缓存

pom.xml引入依赖包

redis.clients

jedis

2.9.0

org.springframework.data

spring-data-redis

2.1.3.RELEASE

其余的依赖包就不贴出来了

java配置目录结构

8be7654ebad2cc9779b9bf6a635e6bfd.png

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);

}

}

b73122ee9332fafff2f3435edf4dc4c8.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值