引入spring-data-redis包、jedis、connection-pool包

applicationContext.xml的配置

    <!-- redis Connection -->
<bean id="redisConnection" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="localhost"></property>
<property name="port" value="6379"></property>
</bean>
<!-- redisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="redisConnection"></property>
</bean>

做一个简单的测试

@Test
public void test1() {
Jedis jd = new Jedis("localhost",6379);
String ping = jd.ping();
System.out.println(ping);
Set<String> keys = jd.keys("*");
for(String k:keys){
System.out.println(k + ":"+ jd.type(k));
}
jd.close(); } @Test
public void test2(){
Jedis j=new Jedis("localhost", 6379);
System.out.println(j.ping());
Set<String> filed= j.hkeys("dept");
System.out.println(filed);
for(String s:filed){
System.out.println(j.hget("dept", s));
}
j.close();
}

自己写一个工具类将,进行序列化与反序列化,

public class SerializableUtil {

    public static byte[] objectToBytes(Object obj) {// 将对象转换为byte数组
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);// 将数据序列化后写入到baos中
byte[] byte1 = baos.toByteArray();
return byte1;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally {
try {
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } public static Object byteToObject(byte[] bytes) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
Object obj = ois.readObject();
return obj; } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally { try {
bais.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

测试:

@Test
public void test4(){ DeptBean bean=new DeptBean(124, "zhangsan1", "shanghai");
Jedis j=new Jedis("localhost", 6379);
j.set("dept".getBytes(), SerializableUtil.objectToBytes(bean));
j.close();
} @Test
public void test5(){
Jedis j=new Jedis("localhost", 6379);
byte[] bean=j.get("dept".getBytes());//获取到的是byte数组
//在将byte数组反序列化
DeptBean byteToObject = (DeptBean) SerializableUtil.byteToObject(bean);
System.out.println(byteToObject);
j.close();
}

上面只是简单的使用自己写的一个工具类进行序列化与反序列化,实际开发中还是使用工具进行的,

写一个控制器,对其进行单元测试

@RunWith(SpringJUnit4ClassRunner.class)//这里的意思是进行一个spring环境的配置
@ContextConfiguration(locations = "classpath:applicationContext.xml")//让其能不启动tomcat服务器的情况下进行测试
public class TestRedis_Data { @Autowired//自动装载
public RedisTemplate<Object, Object> tem; @Test
public void test1() {
// tem.setConnectionFactory(connectionFactory);
// RedisTemplate
DeptBean dept = new DeptBean(10, "傻强", "上海");
tem.opsForValue().set("mydeptsingle", dept);//直接可以设置对象,将其进行序列化
DeptBean object = (DeptBean) tem.opsForValue().get("mydeptsingle");// 底层已经序列化了
System.out.println(object.getDeptno() + " " + object.getDname() + " " + object.getLoc());
} }

然后在对自己有缓存需求的方法进行开启Redis缓存,

//@Controller
@RestController //相当于@Controller 和 @ResponseBody 相结合的功能
public class DeptController { @Autowired //自动装载
private DeptDao dao; //使用redis
@Autowired
private RedisTemplate<Object, Object> temp; @RequestMapping(value = "/dept/all", method = RequestMethod.GET) // @ResponseBody
public List<DeptBean> selectAll() {
List<DeptBean> Deptlist = (List<DeptBean>) temp.opsForValue().get("Deptlist");
List<DeptBean> list = null;
if (Deptlist.isEmpty()) {
list = dao.findAll();
temp.opsForValue().set("Deptlist", list);
return list;
}
return Deptlist;
} // 查询
@RequestMapping(value = "/dept/get", method = RequestMethod.GET)
public DeptBean selelctDeptById(@RequestParam("no") int id) {
// 从Redis中取出来
DeptBean bean = (DeptBean) temp.opsForValue().get("dept" + id);
// 如果没有,从数据库中取出来并返回
if (bean == null) {
System.out.println("从数据库中取");
DeptBean findbean = dao.findId(id);
temp.opsForValue().set("dept" + id, findbean);
return findbean;
}
System.out.println("从缓存中取的数据");
return bean;
} // 分页查询
// 骑牛地址: http://localhost:8060/Spring_Mybatis02/dept/list?page=3&size=3
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
public PageBean pageSelect(
@RequestParam(defaultValue = "1", required = false) int page,
@RequestParam(defaultValue = "5", required = false) int size) {
Page p = PageHelper.startPage(page, size);// 引入jar包中的jar文件,分页只对下一条查询代码有作用 List<DeptBean> list = dao.findAll();
System.out.println("当前页" + p.getPageNum() + " 总页数" + p.getPages() + " 总记录数" + p.getTotal());
PageBean bean = new PageBean();
bean.setList(list);
bean.setPagesize(size);
bean.setTotalpages(p.getPages());
bean.setTotalRecords(p.getTotal());
return bean;
} // 删除
@RequestMapping(value = "/dept/delete", method = RequestMethod.POST)
public int deleteDeptById(int deptno) {
//删除缓存
temp.delete("dept" + deptno);
//从数据库删除
return dao.deleteDeptById(deptno);
}
}

当然如果你需要在项目启动时候就加载到内存中,则可以这样,另写一个专门加载需要缓存的数据

@Component
public class InitLoadData {
@Resource //装载dao层
private DeptDao dao;
@Resource
private RedisTemplate<Object,Object> temp; //装载Redis中的bean配置 @PostConstruct//项目启动时候就会启动该方法 的注解
public void inint(){
System.out.println("查询数据库将数据加载到Redis中");
DeptBean dept=dao.findId(10);
temp.opsForValue().set("dept10", dept); }
}

使用Redis进行简单的数据缓存的更多相关文章

  1. redis实现mysql的数据缓存

    环境设定base2 172.25.78.12 nginx+phpbase3 172.25.78.13 redis端base4 172.25.78.14 mysql端# 1.在base2(nginx+p ...

  2. springboot(12)Redis作为SpringBoot项目数据缓存

    简介: 在项目中设计数据访问的时候往往都是采用直接访问数据库,采用数据库连接池来实现,但是如果我们的项目访问量过大或者访问过于频繁,将会对我们的数据库带来很大的压力.为了解决这个问题从而redis数据 ...

  3. Azure技术系列之Redis篇---第一章数据缓存

    嘈杂和忙碌的生活占据占据了生活的每一天,好久没有静下心来对自己喜欢的技术进行归纳总结了.痛定思痛,今天开始开荒,把之前研究的技术进行归纳总结,先从Azure的Redis的开发技术开始. Azure 的 ...

  4. jQuery源码笔记——数据缓存

    数据缓存是为了解决内存泄露,他的原理是,当我们将数据存储到一个对象上面,实际上是将所有的数据存到一个单独的数据对象里,而这个对象只提供一个接口,这个接口可以访问自己存在数据对象里自己的数据. 这是一个 ...

  5. 企业做数据缓存是使用Memcached还是选Redis?

    企业是使用Memcached还是选Redis? 在构建一款现代且由数据库驱动的Web应用程序并希望使其拥有更为出色的性能表现时,这个问题总会时不时出现.并给每一位开发人员带来困扰.在考虑对应用程序的性 ...

  6. Memcache,Redis,MongoDB(数据缓存系统)方案对比与分析

    mongodb和memcached不是一个范畴内的东西.mongodb是文档型的非关系型数据库,其优势在于查询功能比较强大,能存储海量数据.mongodb和memcached不存在谁替换谁的问题. 和 ...

  7. 老司机带你玩转面试(1):缓存中间件 Redis 基础知识以及数据持久化

    引言 今天周末,我在家坐着掐指一算,马上又要到一年一度的金九银十招聘季了,国内今年上半年受到 YQ 冲击,金三银四泡汤了,这就直接导致很多今年毕业的同学会和明年毕业的同学一起参加今年下半年的秋招,这个 ...

  8. Spring Boot使用redis做数据缓存

    1 添加redis支持 在pom.xml中添加 <dependency> <groupId>org.springframework.boot</groupId> & ...

  9. 学习Spring Boot:(二十五)使用 Redis 实现数据缓存

    前言 由于 Ehcache 存在于单个 java 程序的进程中,无法满足多个程序分布式的情况,需要将多个服务器的缓存集中起来进行管理,需要一个缓存的寄存器,这里使用的是 Redis. 正文 当应用程序 ...

随机推荐

  1. django系列6--Ajax05 请求头ContentType, 使用Ajax上传文件

    一.请求头ContentType ContentType指的是请求体的编码类型,常见的类型共有三种: 1.application/x-www-form-urlencoded 这应该是最常见的 POST ...

  2. Verify the Developer App certificate for your account is trusted on your device.

    1.报错内容 Could not launch "CH5203" Verify the Developer App certificate for your account is ...

  3. 微信小程序转发商品的详情页 + 转发功能(传参)

    1.微信小程序转发传参,利用的还是onShareAppMessageapi 2.利用的还有json转换 JSON 是用于存储和传输数据的格式. JSON 通常用于服务端向网页传递数据 函数 描述JSO ...

  4. zTree第三章,异步加载,前端

    zTree异步加载 ---------------------------------------------------------------------------------- 具体详见API ...

  5. jmeter进行https协议的测试

    一.HTTPS和HTTP的区别     超文本传输协议HTTP协议被用于在Web浏览器和网站服务器之间传递信息.HTTP协议以明文方式发送内容,不提供任何方式的数据加密,如果攻击者截取了Web浏览器和 ...

  6. 8102 年的现代 Web 开发最佳实践(笑)

    简评:8102 年了,现在 web 开发的最佳实践是什么,让本文来告诉你.原文只提到一部分,可以查看 reddit 上对此文的评论查看补充的最佳实践 https://old.reddit.com/r/ ...

  7. RN 中 Native 模块的注入过程

    找到所有的模块 一般来说,只要在模块中声明 RCT_EXPORT_MODULE 即可.这是个宏,展开后是声明了一个函数,定义了两个函数,如下所示. #define RCT_EXPORT_MODULE( ...

  8. 获取指定订阅下所有Azure ARM虚拟机配置(CPU核数,内存大小,磁盘信息)的使用情况

    脚本内容: <# .SYNOPSIS This script grab all ARM VM VHD file in the subscription and caculate VHD size ...

  9. iOS ---进阶之摇一摇

    1.摇一摇的原理分析 1)在摇动手机时会产生一个动画,界面的图片会在中间分开分别进行向上.向下的位置移动. 分析:此过程就是在主屏幕上设置两个imageView,在开始摇动的方法中对这两个imageV ...

  10. 技巧方法 - CentOS6将Python2.6.6升级到Python2.7.6

    1.首先使用“python -V”命令查看python版本,我们测试主机显示的是2.6.6版,于是下面就着手将python2.6.6升级到Python2.7.6.python -V #查看python ...