利用java将数据加入redis缓存

  1. } catch (JedisException e) {

  2. log.info("client can't connect server");

  3. if(null !=jedis){

  4. //redisUtil 对象

  5. redisUtil.brokenResource(jedis);

  6. }

  7. }

  8. return v;

  9. }

  10. @Override

  11. public Map<String, V> hget(String cacheKey,Object object) {

  12. JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象

  13. String jCacheKey = json.toString();//将json对象转换为字符串

  14. //非空校验

  15. if(StringUtils.isEmpty(jCacheKey)){

  16. log.info("cacheKey is empty!");

  17. return null;

  18. }

  19. Jedis jedis =null;

  20. Map<String,V> result =null;

  21. V v=null;

  22. try {

  23. jedis =redisUtil.getResource();

  24. //获取列表集合 因为插入redis的时候是jsonString格式,所以取出来key是String value也是String

  25. Map<String,String> map = jedis.hgetAll(jCacheKey);

  26. if(null !=map){

  27. for(Map.Entry<String, String> entry : map.entrySet()){

  28. if(result ==null){

  29. result =new HashMap<String,V>();

  30. }

  31. JSONObject obj = new JSONObject().fromObject(entry.getValue());//将json字符串转换为json对象

  32. v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象

  33. result.put(entry.getKey(), v);

  34. }

  35. }

  36. } catch (JedisException e) {

  37. log.info("client can't connect server");

  38. if(null !=jedis){

  39. //释放jedis 对象

  40. redisUtil.brokenResource(jedis);

  41. }

  42. }

  43. return result;

  44. }

5.最后我们来测试一下,注意实际开发中肯定是再service层调用redis的操作接口,我这里写个简单的单元测试

第二种:序列化后存入redis, 我这里用SerializeUtil,不过我推荐使用ProtoBuff更好

  1. /**

  2. * Created by ${HeJD} on 2018/6/29.

  3. */

  4. @RunWith(SpringJUnit4ClassRunner.class)

  5. @ContextConfiguration(locations = {"classpath:applicationContext.xml"})

  6. public class RedisCacheStorageTest {

  7. @Autowired

  8. private RedisCacheStorage<String,User> redisCacheStorage;

  9. @Test

  10. public void testSetGet() throws Exception {

  11. System.out.print("开始执行测试");

  12. User user=new User();

  13. user.setUsername("admin7");

  14. user.setPassword("admin8");

  15. redisCacheStorage.set("Akey7",user);

  16. User user2= redisCacheStorage.get("Akey7",new User());

  17. System.out.print("======="+user2.getUsername()+"====="+user2.getPassword());

  18. }

代码在上一种方式的基础之上,我这里只写一些新的文件和需要修改的地方

1.首先我们需要一个序列化类

public class SerializeUtil {

/*

* 序列化

* */

public static byte[] serizlize(Object object){

ObjectOutputStream oos = null;

ByteArrayOutputStream baos = null;

3.最后测试的代码是一样的

(注意两个地方:1.这里是多实现,要用Qualifier指定注入的bean 2.序列化的方式实体类要实现Serializable接口)

2.我们需要对redis操作接口的实现类修改为另一种方式,我这里新建一个RedisCacheStorageImpl2来做对比

  1. @RunWith(SpringJUnit4ClassRunner.class)

  2. @ContextConfiguration(locations = {"classpath:applicationContext.xml"})

  3. public class RedisCacheStorageTest {

  4. @Autowired

  5. @Qualifier("redisCacheStorage2")

  6. private RedisCacheStorage<String,User> redisCacheStorage;

  7. @Test

  8. public void testSet() throws Exception {

  9. System.out.print("开始执行测试");

  10. User user=new User();

  11. user.setUsername("admin9");

  12. user.setPassword("admin12");

  13. redisCacheStorage.set("Akey9",user);

  14. User user2= (User) redisCacheStorage.get("Akey9",new User());

  15. System.out.print("======="+user2.getUsername()+"====="+user2.getPassword());

  16. }

  17. }

  18. package com.mmall.service.impl;

  19. /**

  20. * Created by ${HeJD} on 2018/7/1.

  21. */

  22. import com.mmall.service.RedisCacheStorage;

  23. import com.mmall.util.RedisUtil;

  24. import com.mmall.util.SerializeUtil;

  25. import org.slf4j.Logger;

  26. import org.slf4j.LoggerFactory;

  27. import org.springframework.beans.factory.annotation.Autowired;

  28. import org.springframework.stereotype.Service;

  29. import org.springframework.util.StringUtils;

  30. import redis.clients.jedis.Jedis;

  31. import redis.clients.jedis.exceptions.JedisException;

  32. import java.util.HashMap;

  33. import java.util.Map;

  34. /**

  35. * Created by ${HeJD} on 2018/6/29.

  36. */

  37. @Service("redisCacheStorage2") //这里注入的名称不能相同,方便程序识别

  38. public class RedisCacheStorageImpl2<V> implements RedisCacheStorage<String,V> {

  39. //日志记录

  40. private Logger log= LoggerFactory.getLogger(RedisCacheStorageImpl2.class);

  41. /**

  42. * 默认过时时间

  43. */

  44. private static final int EXPRIE_TIME =3600*24;

  45. /**

  46. * 获取Jedis相关操作

  47. */

  48. @Autowired

  49. private RedisUtil redisUtil;

  50. @Override

  51. public boolean set(String key, V value) {

  52. return set(key,value,EXPRIE_TIME);

  53. }

  54. @Override

  55. public boolean set(String key, V value, int exp) {

  56. Jedis jedis=null;

  57. if(StringUtils.isEmpty(key)){

  58. return false;

  59. }

  60. try {

  61. //获取jedis对象

  62. jedis= redisUtil.getResource();

  63. //序列化对象后插入到redis

  64. //我们需要使用 public String setex(byte[] key, int seconds, byte[] value),所以将key.getBytes()

  65. jedis.setex(key.getBytes(),exp, SerializeUtil.serizlize(value));

  66. }catch (Exception e){

  67. //释放jedis对象

  68. redisUtil.brokenResource(jedis);

  69. log.info("client can't connect server");

  70. return false;

  71. }finally {

  72. //返还连接池

  73. redisUtil.returnResource(jedis);

  74. return true;

  75. }

  76. }

  77. @Override

  78. public V get(String key,Object object) {

  79. Jedis jedis=null;

  80. V v=null;

  81. if(StringUtils.isEmpty(key)){

  82. log.info("redis取值,key为空");

  83. return null;

  84. }

  85. try{

  86. jedis=redisUtil.getResource(); //获取连接

  87. //我们存入的时候使用的是key.getBytes(),所以取的时候也要使用它的key数组

  88. byte valueByte[]=jedis.get(key.getBytes()); //从redis得到值

  89. if(valueByte.length<=0){

  90. return null;

  91. }

  92. //反序列化取出我们的数据

  93. v=(V)SerializeUtil.deserialize(valueByte); //将值转换为我们插入redis之前的数据类型

  94. return v;

  95. }catch (Exception e){

  96. //释放jedis对象

  97. if(jedis!=null){

  98. redisUtil.brokenResource(jedis);

  99. }

  100. log.info("client can't get value");

  101. return null;

  102. }finally {

  103. //返还连接池

  104. redisUtil.returnResource(jedis);

  105. }

  106. }

  107. @Override

  108. public boolean remove(String key) {

  109. Jedis jedis=null;

  110. try{

  111. jedis=redisUtil.getResource();

  112. if(StringUtils.isEmpty(key)){

  113. log.info("redis取值,key为空");

  114. return false;

  115. }

  116. jedis.del(key.getBytes());

  117. }catch (Exception e) {

  118. //释放jedis对象

  119. if(jedis!=null){

  120. redisUtil.brokenResource(jedis);

  121. }

  122. log.info(" del fail from redis");

  123. return false;

  124. }finally{

  125. //返还连接池

  126. redisUtil.returnResource(jedis);

  127. return true;

  128. }

  129. }

  130. @Override

  131. public boolean hset(String cacheKey, String key, V value) {

  132. Jedis jedis =null;

  133. byte valueDate[]= SerializeUtil.serizlize(value);

  134. //操作是否成功

  135. boolean isSucess =true;

  136. if(StringUtils.isEmpty(cacheKey)){

  137. log.info("cacheKey is empty");

  138. return false;

  139. }

  140. try {

  141. jedis =redisUtil.getResource();

  142. //执行插入哈希

  143. //public Long hset(byte[] key, byte[] field, byte[] value)

  144. jedis.hset(cacheKey.getBytes(),key.getBytes(),valueDate);

  145. } catch (Exception e) {

  146. log.info("client can't connect server");

  147. isSucess =false;

  148. if(null !=jedis){

  149. //释放jedis 对象

  150. redisUtil.brokenResource(jedis);

  151. }

  152. return false;

  153. }finally{

  154. if (isSucess) {

  155. //返还连接池

  156. redisUtil.returnResource(jedis);

  157. }

  158. return true;

  159. }

  160. }

  161. @Override

  162. public V hget(String cacheKey, String key,Object object) {

  163. Jedis jedis =null;

  164. V v =null;

  165. if(cacheKey.getBytes().length<=0){

  166. log.info("cacheKey is empty");

  167. return null;

  168. }

  169. try {

  170. //获取客户端对象

  171. jedis =redisUtil.getResource();

  172. //执行查询

  173. byte valueDate[] = jedis.hget(cacheKey.getBytes(), key.getBytes());

  174. //判断值是否非空

  175. if(valueDate.length<0){

  176. return null;

  177. }else{

  178. //反序列化拿到数据

  179. v= (V)SerializeUtil.deserialize(valueDate);

  180. return v;

  181. }

  182. } catch (JedisException e) {

  183. log.info("client can't connect server");

  184. if(null !=jedis){

  185. //redisUtil 对象

  186. redisUtil.brokenResource(jedis);

  187. }

  188. }finally {

  189. //返还连接池

  190. redisUtil.returnResource(jedis);

  191. }

  192. return v;

  193. }

  194. @Override

  195. public Map<String, V> hget(String cacheKey,Object object) {

  196. //非空校验

  197. if(StringUtils.isEmpty(cacheKey)){

  198. log.info("cacheKey is empty!");

  199. return null;

  200. }

  201. Jedis jedis =null;

  202. Map<String,V> result =new HashMap<String,V>();

  203. try {

  204. jedis =redisUtil.getResource();

  205. //获取列表集合 因为插入redis的时候是key和value都是字节数组,所以返回的结果也是字节数组

  206. Map<byte[], byte[]> map= jedis.hgetAll(cacheKey.getBytes());

  207. if(null !=map){

  208. for(Map.Entry<byte[], byte[]> entry : map.entrySet()){

  209. result.put(new String(entry.getKey()),(V)SerializeUtil.deserialize(entry.getValue()));

  210. }

  211. }

  212. } catch (JedisException e) {

  213. log.info("client can't connect server");

  214. if(null !=jedis){

  215. //释放jedis 对象

  216. redisUtil.brokenResource(jedis);

  217. }

  218. }

  219. return result;

  220. }

  221. }

  222. try {

  223. baos = new ByteArrayOutputStream();

  224. oos = new ObjectOutputStream(baos);

  225. oos.writeObject(object);

  226. byte[] bytes = baos.toByteArray();

  227. return bytes;

  228. } catch (Exception e) {

  229. e.printStackTrace();

  230. }finally {

  231. try {

  232. if(baos != null){

  233. baos.close();

  234. }

  235. if (oos != null) {

  236. oos.close();

  237. }

  238. } catch (Exception e2) {

  239. e2.printStackTrace();

  240. }

  241. }

  242. return null;

  243. }

  244. /*

  245. * 反序列化

  246. * */

  247. public static Object deserialize(byte[] bytes){

  248. ByteArrayInputStream bais = null;

  249. ObjectInputStream ois = null;

  250. try{

  251. bais = new ByteArrayInputStream(bytes);

  252. ois = new ObjectInputStream(bais);

  253. return ois.readObject();

  254. }catch(Exception e){

  255. e.printStackTrace();

  256. }finally {

  257. try {

  258. } catch (Exception e2) {

  259. e2.printStackTrace();

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

总结

我们总是喜欢瞻仰大厂的大神们,但实际上大神也不过凡人,与菜鸟程序员相比,也就多花了几分心思,如果你再不努力,差距也只会越来越大。实际上,作为程序员,丰富自己的知识储备,提升自己的知识深度和广度是很有必要的。

Mybatis源码解析

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门即可获取!

  1. ByteArrayInputStream bais = null;

  2. ObjectInputStream ois = null;

  3. try{

  4. bais = new ByteArrayInputStream(bytes);

  5. ois = new ObjectInputStream(bais);

  6. return ois.readObject();

  7. }catch(Exception e){

  8. e.printStackTrace();

  9. }finally {

  10. try {

  11. } catch (Exception e2) {

  12. e2.printStackTrace();

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。[外链图片转存中…(img-g9MzUdSC-1711901646490)]

[外链图片转存中…(img-sDZiVYrM-1711901646490)]

[外链图片转存中…(img-sCenvZ4c-1711901646490)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

总结

我们总是喜欢瞻仰大厂的大神们,但实际上大神也不过凡人,与菜鸟程序员相比,也就多花了几分心思,如果你再不努力,差距也只会越来越大。实际上,作为程序员,丰富自己的知识储备,提升自己的知识深度和广度是很有必要的。

Mybatis源码解析

[外链图片转存中…(img-9SPahrDl-1711901646491)]

[外链图片转存中…(img-Dp0fUJ6p-1711901646491)]

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门即可获取!

  • 25
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值