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

java配置SSM框架下的redis缓存的更多相关文章

  1. SSM框架下的redis缓存

    基本SSM框架搭建:http://www.cnblogs.com/fuchuanzhipan1209/p/6274358.html 配置文件部分: 第一步:加入jar包 pom.xml <!-- ...

  2. 关于在SSM框架下使用PageHelper

    首先,如果各位在这块配置和代码有什么问题欢迎说出来,我也会尽自己最大的能力帮大家解答 这些代码我都是写在一个小项目里的,项目的github地址为:https://github.com/Albert-B ...

  3. Java基于ssm框架的restful应用开发

    Java基于ssm框架的restful应用开发 好几年都没写过java的应用了,这里记录下使用java ssm框架.jwt如何进行rest应用开发,文中会涉及到全局异常拦截处理.jwt校验.token ...

  4. ssm框架下怎么批量删除数据?

    ssm框架下批量删除怎么删除? 1.单击删除按钮选中选项后,跳转到js函数,由函数处理 2. 主要就是前端的操作 js 操作(如何全选?如何把选中的数据传到Controller中) 3.fun()函数 ...

  5. Yii框架下使用redis做缓存,读写分离

    Yii框架中内置好几个缓存类,其中有memcache的类,但是没有redis缓存类,由于项目中需要做主从架构,所以扩展了一下: /** * FileName:RedisCluster * 配置说明 * ...

  6. SSM框架下分页的实现(封装page.java和List<?>)

    之前写过一篇博客  java分页的实现(后台工具类和前台jsp页面),介绍了分页的原理. 今天整合了Spring和SpringMVC和MyBatis,做了增删改查和分页,之前的逻辑都写在了Servle ...

  7. JAVA:ssm框架搭建

    文章来源:http://www.cnblogs.com/hello-tl/p/8328071.html 环境简介 : jdk1.7.0_25/jdk1.8.0_31  tomcat-7.0.81  m ...

  8. Windows环境下使用Redis缓存工具的图文详细方法

    一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...

  9. ssm框架下实现文件上传

      1.由于ssm框架是使用Maven进行管理的,文件上传所需要的jar包利用pom.xml进行添加,如下所示: <properties> <commons-fileupload.v ...

随机推荐

  1. web开发:jquery之DOM

    一.文档结构 二.文档操作 三.文档操作案例 四.form表单 五.正则 六.form案例 一.文档结构 ```jsvar $sup = $('.sup');console.log($sup.chil ...

  2. 将excel表格导入到DataGridView

    using System.Data.OleDb; 添加一个button控件,一个textBox控件,用于显示选择路径  private void loadxls() { String fileName ...

  3. java8 常用语法小结

    // 判空 // 排序 //映射 //序列化

  4. celery+django+mq 异步任务与定时任务

    参考 celerypip install celery==4.1.1https://www.cnblogs.com/wdliu/p/9530219.htmlhttps://www.jianshu.co ...

  5. git log master..origin/master --oneline | wc -l 怎么知道本地仓库是不是最新的

    git log master..origin/master --oneline | wc -l 怎么知道本地仓库是不是最新的 git fetch   # 一定要先 fetch git log mast ...

  6. 【CF1218E】Product Tuples

    题目大意:给定一个长度为 \(N\) 的序列,求从序列中选出 \(K\) 个数的集合乘积之和是多少. 题解: 由于是选出 \(K\) 个数字组成的集合,可知对于要计算的 \(K\) 元组来说是没有标号 ...

  7. python解决八皇后问题的方法

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/9/11 15:40 # @Author : Lijinjin # @Site ...

  8. WinForm DevExpress使用之ChartControl控件绘制图表二——进阶

    1. 多坐标折线图 在这个项目中,我需要做不同采集地方和不同数据类型的数据对比,自然而然就用到了多重坐标轴,多重坐标轴可以是多个X轴,也可以是Y轴,它们的处理方式类似.本文通过项目中的实际例子介绍多重 ...

  9. python之select与selector

    select/poll/epoll的区别 I/O多路复用的本质就是用select/poll/epoll,去监听多个socket对象. 参考:Linux IO模式及 select.poll.epoll详 ...

  10. Hdu 4333 Revolving Digits(Exkmp)

    Revolving Digits Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) To ...