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. pxc5.7 报错:WSREP_SST: [ERROR] xtrabackup_checkpoints missing

    PXC 5.7 WSREP_SST: [ERROR] xtrabackup_checkpoints missing PXC5.7,在启动其中的一个节点,碰到了 [ERROR] xtrabackup_c ...

  2. 团队项目-Beta版本发布

    这个作业属于哪个课程 课程链接 这个作业要求在哪里 作业要求链接 团队名称 众志陈成 这个作业的目标 通过团队协作了解软件开发的大致流程,并在这个过程中体会调整与优化程序的方法,为以后真实的软件开发奠 ...

  3. redis + boost.asio

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

  4. 箭头函数与定时器的this指向问题

    函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象. 箭头函数本身没有this,this继承上级的this. 定时器中箭头函数的this指向包含定时器的函数,所以定时器中的箭头函数要 ...

  5. 详解Object.create(null)

    在Vue和Vuex的源码中,作者都使用了Object.create(null)来初始化一个新对象.为什么不用更简洁的{}呢? 在SegmentFault和Stack Overflow等开发者社区中也有 ...

  6. 脚本实现PXE装机

    #!/bin/bash read -p "请输入您的装机服务器:" ip read -p "请输入您想要的ip最小值(1-255):" min read -p ...

  7. B/S上传大文件的解决方案

    第一点:Java代码实现文件上传 FormFile file = manform.getFile(); String newfileName = null; String newpathname =  ...

  8. 【csp模拟赛5】购物(shopping.cpp)--常规

    多项式,因为每次的x相同,所以把a和b相加就行了,然后找对称轴,找离对称轴最近的整数点,然而我却写了个暴力,没看x #include <iostream> #include <cst ...

  9. codeforces708C

    CF708C Centroids 题意翻译 给定一颗树,你有一次将树改造的机会,改造的意思是删去一条边,再加入一条边,保证改造后还是一棵树. 请问有多少点可以通过改造,成为这颗树的中心?(如果以某个点 ...

  10. JVM GC之垃圾收集器

    简述 如果说收集算法时内存回收的方法论,那么垃圾收集器就是内存回收的具体实现.这里我们讨论的垃圾收集器是基于JKD1.7之后的Hotspot虚拟机,这个虚拟机包含的所有收集器如图: Serial 收集 ...