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. docker 搭建zookeeper集群和kafka集群

    docker 搭建zookeeper集群 安装docker-compose容器编排工具 Compose介绍 Docker Compose 是 Docker 官方编排(Orchestration)项目之 ...

  2. oracle 初试 hint

    最近在研究oracle的视图问题,本来想全转成 物化视图(materialized view)的,这样可以极大提升系统的响应时间,无奈工作量太大,所以就研究了SQL优化的问题. 我这个普通视图 有36 ...

  3. iview 如何在表格中给操作图标添加Tooltip文字提示?

    项目需要用到的iview 表格中操作项目有各种各样的图标,而各种各样的图标代表不同的操作,面对新用户可能很懵,那如何给这些图标添加Tooltip文字提示? 废话不多讲,直接看代码: <templ ...

  4. linux下top命令的使用

    top命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器 视图参数含义 top视图分为两部分:操作系统资源概况信息和进程信息.首先分析资源 ...

  5. Go语言关于Type Assertions的疑问

    我在"The Go Programming Language Specification"中读到了关于x.(T)这样的语法可以对变量是否符合某一type或interface进行判断 ...

  6. string::assign

    string (1) string& assign (const string& str); substring (2) string& assign (const strin ...

  7. 冒泡排序Bubble_Sort

    基本原理:对于冒泡排序来说,基本思想是从第一个元素开始,数组中的数据依次和它后面相邻的数据进行比较,即1和2比较,2和3比较,a和a+1比较,直到倒数第二位和倒数第一位的比较,如果顺序不对就进行交换, ...

  8. vue 日期格式化过滤器

    formateDate日期格式化,写在公共的js中: export function formateDate(date, fmt){ if ('/(y+)/'.test(fmt){ fmt = fmt ...

  9. MacOs High Sierra 升级失败解决办法

    进入recovery的方法: Command-R 重新安装您在 Mac 上安装过的最新 macOS,但不会升级到更高的版本. Option-Command-R升级到与您的 Mac 兼容的最新 macO ...

  10. 使用StringBuilder写XML遭遇UTF-16问题

     http://www.cnblogs.com/jans2002/archive/2007/08/05/843843.html