1.导入依赖

<properties>
<junit.version>4.12</junit.version>
<spring.version>4.2.4.RELEASE</spring.version>
</properties> <dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<!--Redis依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
</dependencies>

2.在resources文件夹下添加配置文件

redis-config.properties

redis.host=192.168.200.128
redis.port=6379
#redis有验证添加,无验证不添加
redis.pass=
redis.database=0
redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=true

applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd"> <context:property-placeholder location="classpath*:redis-config.properties" /> <!-- redis 相关配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean> <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="JedisConnectionFactory" />
</bean> </beans>

3.测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/spring/applicationContext-redis.xml")
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate; //1.redis简单数据类型
@Test
public void test01(){ redisTemplate.opsForValue().set("key1", "华为"); //向redis中添加数据
String key1 = (String) redisTemplate.opsForValue().get("key1"); //获取redis中的数据
System.out.println(key1); redisTemplate.delete("key1"); //删除redis中的数据
Object key2 = redisTemplate.opsForValue().get("key1"); //获取redis中的数据
System.out.println(key2); //若redis中无对应的值,则返回null
}
//2.redis值类型操作
@Test
public void test02(){
redisTemplate.boundValueOps("key").set("spring-data-redis"); //向redis中添加数据
Object key = redisTemplate.boundValueOps("key").get(); //获取redis中的数据
System.out.println(key); redisTemplate.delete("key"); //删除redis中的数据
Object key1 = redisTemplate.boundValueOps("key").get(); //获取redis中的数据
System.out.println(key1); //若redis中无对应的值,则返回null
} //3.redis Set类型操作
@Test
public void test03(){
redisTemplate.boundSetOps("set").add("华为");
redisTemplate.boundSetOps("set").add("苹果");
redisTemplate.boundSetOps("set").add("三星");
redisTemplate.boundSetOps("set").add("小米");
redisTemplate.boundSetOps("set").add("vivo");
redisTemplate.boundSetOps("set").add("魅族"); Set set = redisTemplate.boundSetOps("set").members();
System.out.println(set); //redisTemplate.boundSetOps("set").remove("魅族");
redisTemplate.delete("set");
Set set1 = redisTemplate.boundSetOps("set").members();
System.out.println(set1);
}
//4.redis List类型操作
@Test
public void test04(){
redisTemplate.boundListOps("list").leftPush("a"); //从左边添加数据
redisTemplate.boundListOps("list").leftPush("b");
redisTemplate.boundListOps("list").leftPush("c");
redisTemplate.boundListOps("list").rightPush("1"); //从右边添加数据
redisTemplate.boundListOps("list").rightPush("2");
redisTemplate.boundListOps("list").rightPush("3"); List list = redisTemplate.boundListOps("list").range(0, -1);
System.out.println(list); redisTemplate.delete("list");
List list1 = redisTemplate.boundListOps("list").range(0, -1);
System.out.println(list1); }
//5.Hash类型操作
@Test
public void test05(){
redisTemplate.boundHashOps("hash").put("name", "张三");
redisTemplate.boundHashOps("hash").put("sex", "男");
redisTemplate.boundHashOps("hash").put("age", "18"); Map map = redisTemplate.boundHashOps("hash").entries();
for (Object key : map.keySet()) {
System.out.println(key +" : " + map.get(key) );
}
redisTemplate.boundHashOps("hash").delete("sex");
Map map1 = redisTemplate.boundHashOps("hash").entries();
for (Object o : map1.entrySet()) {
Map.Entry entry = (Map.Entry) o;
System.out.println(entry.getKey()+":"+entry.getValue());
} }
}

4.项目中的使用

先从redis中查询数据,若为null,则表示redis中无数据,然后从mysql数据库中查找数据,再将数据存入redis缓存中。数据库进行增删改操作之后都要清除redis缓存,以防数据不一致。

public class ContentServiceImpl implements ContentService {
@Autowired
private ContentMapper contentMapper;
@Autowired
private RedisTemplate redisTemplate;
@Override
public void insert(Content content) { //redis缓存
contentMapper.insertSelective(content);
//清楚缓存
redisTemplate.boundHashOps(RedisConst.CONTENT).delete(content.getCategoryId());
} @Override
public void delete(Long[] ids) {
//清空缓存
for (Long id : ids) {
Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();
redisTemplate.boundHashOps(RedisConst.CONTENT).delete(categoryId);
} //从数据库删除记录
List<Long> list = Arrays.asList(ids);
ContentExample example = new ContentExample();
example.createCriteria().andIdIn(list);
contentMapper.deleteByExample(example);
} @Override
public void update(Content content) {
//查询修改前的分类id
Long oldCategoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
redisTemplate.boundHashOps(RedisConst.CONTENT).delete(oldCategoryId); //清除缓存
contentMapper.updateByPrimaryKeySelective(content); //如果修改后的分类id发生修改,清除修改后的分类id的缓存
if(oldCategoryId.longValue() != content.getCategoryId().longValue()){
redisTemplate.boundHashOps(RedisConst.CONTENT).delete(content.getCategoryId());
}
}
//根据广告分类id查询广告列表
@Override
public List<Content> findByCategoryId(long categoryId) { //redis缓存机制
//1.从redis中取数据
List<Content> contents = (List<Content>) redisTemplate.boundHashOps(RedisConst.CONTENT).get(categoryId);
//2.判断redis中是否有数据
if(contents == null){
//3.从mysql数据库中查找数据
ContentExample example = new ContentExample();
ContentExample.Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(categoryId);
criteria.andStatusEqualTo("1");//开启状态
example.setOrderByClause("sort_order");
contents = contentMapper.selectByExample(example);
//4.将查询到的数据库保存到Redis数据库中
redisTemplate.boundHashOps(RedisConst.CONTENT).put(categoryId, contents);
}
return contents;
} }

spring-data-redis的使用/redis缓存的更多相关文章

  1. 使用Spring Data Redis时,遇到的几个问题

    需求: 1,保存一个key-value形式的结构到redis 2,把一个对象保存成hash形式的结构到redis 代码如下: // 保存key-value值         pushFrequency ...

  2. hibernate、mybatis、spring data 的对比

    转: 1.概念: Hibernate :Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库.着力 ...

  3. ORM--------Hibernate、Mybatis与Spring Data的区别

    1.概念: Hibernate :Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库.着力点对象 ...

  4. 使用 Spring data redis 结合 Spring cache 缓存数据配置

    使用 JavaConfig 方式配置 依赖 jar 包: jedis.spring-data-redis 首先需要进行 Redis 相关配置 @Configuration public class R ...

  5. 分布式缓存技术redis学习系列(五)——redis实战(redis与spring整合,分布式锁实现)

    本文是redis学习系列的第五篇,点击下面链接可回看系列文章 <redis简介以及linux上的安装> <详细讲解redis数据结构(内存模型)以及常用命令> <redi ...

  6. spring + redis 实现数据的缓存

    1.实现目标 通过redis缓存数据.(目的不是加快查询的速度,而是减少数据库的负担) 2.所需jar包 注意:jdies和commons-pool两个jar的版本是有对应关系的,注意引入jar包是要 ...

  7. spring data redis RedisTemplate操作redis相关用法

    http://blog.mkfree.com/posts/515835d1975a30cc561dc35d spring-data-redis API:http://docs.spring.io/sp ...

  8. Spring data redis的一个bug

    起因 前两天上线了一个新功能,导致线上业务的缓存总是无法更新,报错也是非常奇怪,redis.clients.jedis.exceptions.JedisConnectionException: Unk ...

  9. Spring Data操作Redis详解

    Spring Data操作Redis详解 Redis是一种NOSQL数据库,Key-Value形式对数据进行存储,其中数据可以以内存形式存在,也可以持久化到文件系统.Spring data对Redis ...

  10. Spring Data Redis 让 NoSQL 快如闪电(2)

    [编者按]本文作者为 Xinyu Liu,文章的第一部分重点概述了 Redis 方方面面的特性.在第二部分,将介绍详细的用例.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 把 Redis ...

随机推荐

  1. 2--面试总结-深入理解js线程进阶-宏任务微任务

    前言:Event Loop即时间循环,是指浏览器或Node的一种解决javascript单线程运行时不会阻塞的一种机制,也就是我们经常使用异步的原理 Js运行机制      1.不同运行环境,js运行 ...

  2. 带加载进度的Web图片懒加载组件Lazyload

    在Web项目中,大量的图片应用会导致页面加载时间过长,浪费不必要的带宽成本,还会影响用户浏览体验. Lazyload 是一个文件大小仅4kb的图片懒加载组件(不依赖其它第三方库),组件会根据用户当前浏 ...

  3. Quantitative Startegies for Achieving Alpha(二)

    Chapter 3 The Day-To-Day Drivers Of Stock Market Returns Summary: (1) Earning growth is the primary ...

  4. vs 2010创建Windows服务定时timer程序

    vs 2010创建Windows服务定时timer程序: 版权声明:本文为搜集借鉴各类文章的原创文章,转载请注明出处:  http://www.cnblogs.com/2186009311CFF/p/ ...

  5. css雪碧图-css精灵图

    先将图片拼接在一张图上.类似实现的效果图 图片地址为合并后的图片地址,通过background-position调整背景图的位置.效果如: HTML: <div class="logo ...

  6. 重塑云上的 Java 语言

    音乐无国界,但是音乐人有国界. 云原生亦如此.虽没有限定的编程语言,但应用所使用的编程语言已经决定了应用部署运行的行为. Java 诞生于20年前,拥有大量优秀的企业级框架,践行 OOP 理念,更多体 ...

  7. 阿里云 Serverless 应用引擎(SAE)发布 v1.2.0,支持一键启停、NAS 存储、小规格实例等实用特性

    近日,阿里云 Serverless 应用引擎(SAE)发布 v1.2.0版本,新版本实现了以下新功能/新特性: 一键启停开发测试环境:企业开发测试环境一般晚上不常用,长期保有应用实例,闲置浪费很高.使 ...

  8. 判断div里面的子集是否含有特定的类

    if($('#BankCardId .card').length){ alert("请绑定银行卡"); } if ($('#user-20130011 #age-20130011' ...

  9. String、StringBuffer与StringBuilder介绍

    关于这三个类在字符串处理中的位置不言而喻,那么他们到底有什么优缺点,到底什么时候该用谁呢?下面我们从以下几点说明一下 1.三者在执行速度方面的比较:     StringBuilder > St ...

  10. 3D Computer Grapihcs Using OpenGL - 09 Enable Depth Test

    启用Depth Test OpenGL是个3D绘图API,也就是说不只有xy坐标轴,还有第三个坐标轴z,z轴的方向是垂直于屏幕,指向屏幕内. 靠近人眼的方向是负方向,标准化设备坐标的最小值是-1, 最 ...