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. python 中的GIL (全局解释器锁)详解

    1.GIL是什么? GIL全称Global Interpreter Lock,即全局解释器锁. 作用就是,限制多线程同时执行,保证同一时间内只有一个线程在执行. GIL并不是Python的特性,它是在 ...

  2. python Flask中html模版中如何引用css,js等资源

    已有静态页面,需要将其整合到瓶的项目中,需要搞清楚, 之前的HTML中的: <link rel =“stylesheet”href =“css / framework7.ios.css”> ...

  3. 常量和iota

    定义常量时如果不是必须指定特定类型,可以省略类型,使用默认类型.且数值类型常量(不定义类型)可以直接进行运算 常量的值可以是表达式,但是不允许出现变量 func main() { const a st ...

  4. FFmpeg常用命令学习笔记(三)分解/复用命令

    分解/复用命令 比如文件格式的转换.将封装格式文件中的音频与视频文件分别抽取出来等. 多媒体格式的转换(将MP4文件转成flv格式) ffmpeg -i yan.mp4 -vcodec copy -a ...

  5. oracle impdp 覆盖导入 table_exists_action关键字使用

    oracle10g之后impdp的table_exists_action参数table_exists_action选项:{skip 是如果已存在表,则跳过并处理下一个对象:append是为表增加数据: ...

  6. Linux查找文件内容小技巧

    目录 grep ag linux系统查找文件内容最常见的命令有grep和ag grep grep是比较常见的查找命令 # 在当前目录的py文件里查找所有相关内容 grep -a "broad ...

  7. 【方法】如何实现图片压缩并使用FormData上传

    在前端上传图片的操作过程中,当上传服务器时,如果图片过大,可能会影响页面响应速度,这个时候,我们便会对图片进行压缩处理,再上传服务器. 前端对图片进行压缩,一般使用canvas来实现.最后使用canv ...

  8. PHP mysqli_field_seek() 函数

    定义和用法 mysqli_field_seek() 函数把字段指针设置为指定字段的偏移量. 设置结果集中第一个字段(列)的字段指针,然后通过 mysqli_fetch_field() 获取字段信息并输 ...

  9. MSMQ使用

    Message Message是MSMQ的数据存储单元,我们的用户数据一般也被填充在Message的body当中,因此很重要,让我们来看一看其在.net中的体现,如图: 在图上我们可以看见,Messa ...

  10. 【线性代数】2-3:消元与矩阵的关系(Elimination and Matrix)

    title: [线性代数]2-3:消元与矩阵的关系(Elimination and Matrix) toc: true categories: Mathematic Linear Algebra da ...