java配置SSM框架下的redis缓存
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缓存的更多相关文章
- SSM框架下的redis缓存
基本SSM框架搭建:http://www.cnblogs.com/fuchuanzhipan1209/p/6274358.html 配置文件部分: 第一步:加入jar包 pom.xml <!-- ...
- 关于在SSM框架下使用PageHelper
首先,如果各位在这块配置和代码有什么问题欢迎说出来,我也会尽自己最大的能力帮大家解答 这些代码我都是写在一个小项目里的,项目的github地址为:https://github.com/Albert-B ...
- Java基于ssm框架的restful应用开发
Java基于ssm框架的restful应用开发 好几年都没写过java的应用了,这里记录下使用java ssm框架.jwt如何进行rest应用开发,文中会涉及到全局异常拦截处理.jwt校验.token ...
- ssm框架下怎么批量删除数据?
ssm框架下批量删除怎么删除? 1.单击删除按钮选中选项后,跳转到js函数,由函数处理 2. 主要就是前端的操作 js 操作(如何全选?如何把选中的数据传到Controller中) 3.fun()函数 ...
- Yii框架下使用redis做缓存,读写分离
Yii框架中内置好几个缓存类,其中有memcache的类,但是没有redis缓存类,由于项目中需要做主从架构,所以扩展了一下: /** * FileName:RedisCluster * 配置说明 * ...
- SSM框架下分页的实现(封装page.java和List<?>)
之前写过一篇博客 java分页的实现(后台工具类和前台jsp页面),介绍了分页的原理. 今天整合了Spring和SpringMVC和MyBatis,做了增删改查和分页,之前的逻辑都写在了Servle ...
- JAVA:ssm框架搭建
文章来源:http://www.cnblogs.com/hello-tl/p/8328071.html 环境简介 : jdk1.7.0_25/jdk1.8.0_31 tomcat-7.0.81 m ...
- Windows环境下使用Redis缓存工具的图文详细方法
一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...
- ssm框架下实现文件上传
1.由于ssm框架是使用Maven进行管理的,文件上传所需要的jar包利用pom.xml进行添加,如下所示: <properties> <commons-fileupload.v ...
随机推荐
- Linux--查询文件的第几行到第几行命令
cat catalina.out | tail -n +14000 | head -n 10000 | sort | uniq -c linux 如何显示一个文件的某几行(中间几行)[一]从第3000 ...
- cifs
加入cifs 能把设备的目录挂载到我们的电脑上面 mount -t cifs -o username=Everyone //192.168.23.72/cifs /cif 如果当前是everyone ...
- wkhtmltopdf 自定义字体未生效或中文乱码
使用wkhtmltopdf控件将网页保存成pdf的过程中出现网页中有些字体,在PDF中未生效.通过网上查询结果有一种处理方式: 在网页头部的style标签中,手工指定宋体字体的本地存放位置,wkhtm ...
- (五)zabbix微信报警
1.注册微信企业号 1)注册微信企业号 https://work.weixin.qq.com 2)通讯录添加用户 3)记住部门id 4)创建应用 5)点击刚创建的应用,记住Agentld和secret ...
- 218多校第九场 HDU 6424 (数学)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6424 题意:定义f(A) = log log log log …. (A个log) n ,g[A,B, ...
- .net System.Net.Mail 之用SmtpClient发送邮件Demo
private static bool sendMail() { try { //接收人邮箱 string SendTo = "XXXXX@163.com ...
- 019_linuxC++之_函数模板引入
(一)首先我们来看非模板程序,函数只是输入不一样的变量就需要构件很多个不一样的函数,那么这样很麻烦,则引入函数模板 int& max(int& a, int& b) { ret ...
- java+上传整个文件夹的所有文件
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- HDU 5852 Intersection is not allowed! ( 2016多校9、不相交路径的方案、LGV定理、行列式计算 )
题目链接 题意 : 给定方格中第一行的各个起点.再给定最后一行与起点相对应的终点.问你从这些起点出发到各自的终点.不相交的路径有多少条.移动方向只能向下或向右 分析 : 首先对于多起点和多终点的不相交 ...
- Python面试题:使用栈处理括号匹配问题
括号匹配是栈应用的一个经典问题, 题目 判断一个文本中的括号是否闭合, 如: text = "({[({{abc}})][{1}]})2([]){({[]})}[]", 判断所有括 ...