最近在研究redis也结合了许多网上的资料分享给大家,有些不足的还望大家多补充提点,下面直接进入主题。

结构图:

几个redis的核心jar,spring的一些jar自行导入

接下来开始配置项目:

1、配置文件

redis.properties

  1. redis.host = 192.168.76.76
  2. redis.port = 6379
  3. redis.pass = admin
  4. redis.maxIdle = 200
  5. redis.maxActive = 1024
  6. redis.maxWait = 10000
  7. redis.testOnBorrow = true

spring-redis.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xmlns:jee="http://www.springframework.org/schema/jee"
  8. xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  9. xmlns:cache="http://www.springframework.org/schema/cache"
  10. xmlns:jaxws="http://cxf.apache.org/jaxws"
  11. xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  12. xsi:schemaLocation="http://www.springframework.org/schema/beans
  13. http://www.springframework.org/schema/beans/spring-beans.xsd
  14. http://www.springframework.org/schema/tx
  15. http://www.springframework.org/schema/tx/spring-tx.xsd
  16. http://www.springframework.org/schema/context
  17. http://www.springframework.org/schema/context/spring-context.xsd
  18. http://www.springframework.org/schema/aop
  19. http://www.springframework.org/schema/aop/spring-aop.xsd
  20. http://www.springframework.org/schema/jee
  21. http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
  22. http://www.springframework.org/schema/jdbc
  23. http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
  24. http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
  25. http://cxf.apache.org/jaxws
  26. http://cxf.apache.org/schemas/jaxws.xsd
  27. http://cxf.apache.org/jaxrs
  28. http://cxf.apache.org/schemas/jaxrs.xsd" default-autowire="byName" >
  29.  
  30. <!-- 引入配置文件 -->
  31. <context:property-placeholder location="classpath:/resource/redis.properties"/>
  32.  
  33. <!-- 连接池基本参数配置,类似数据库连接池 -->
  34. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  35. <property name="maxIdle" value="${redis.maxIdle}" />
  36. <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
  37. </bean>
  38.  
  39. <!-- 连接池配置,类似数据库连接池 -->
  40. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
  41. <property name="hostName" value="${redis.host}"></property>
  42. <property name="port" value="${redis.port}"></property>
  43. <property name="password" value="${redis.pass}"></property>
  44. <property name="poolConfig" ref="poolConfig"></property>
  45. </bean>
  46.  
  47. <!-- 调用连接池工厂配置 -->
  48. <bean id="redisTemplate" class=" org.springframework.data.redis.core.RedisTemplate">
  49. <property name="connectionFactory" ref="connectionFactory"></property>
  50. <!-- 自定义json序列化存储 -->
  51. <!-- <property name="defaultSerializer">
  52. <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
  53. </property> -->
  54.  
  55. <!-- 如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can't cast
  56. to String!!! -->
  57. <property name="keySerializer">
  58. <bean
  59. class="org.springframework.data.redis.serializer.StringRedisSerializer" />
  60. </property>
  61. <property name="valueSerializer">
  62. <bean
  63. class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
  64. </property>
  65. </bean>
  66. </beans>

spring-source.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xmlns:jee="http://www.springframework.org/schema/jee"
  8. xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  9. xmlns:cache="http://www.springframework.org/schema/cache"
  10. xmlns:jaxws="http://cxf.apache.org/jaxws"
  11. xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  12. xsi:schemaLocation="http://www.springframework.org/schema/beans
  13. http://www.springframework.org/schema/beans/spring-beans.xsd
  14. http://www.springframework.org/schema/tx
  15. http://www.springframework.org/schema/tx/spring-tx.xsd
  16. http://www.springframework.org/schema/context
  17. http://www.springframework.org/schema/context/spring-context.xsd
  18. http://www.springframework.org/schema/aop
  19. http://www.springframework.org/schema/aop/spring-aop.xsd
  20. http://www.springframework.org/schema/jee
  21. http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
  22. http://www.springframework.org/schema/jdbc
  23. http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
  24. http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
  25. http://cxf.apache.org/jaxws
  26. http://cxf.apache.org/schemas/jaxws.xsd
  27. http://cxf.apache.org/jaxrs
  28. http://cxf.apache.org/schemas/jaxrs.xsd" default-autowire="byName" >
  29.  
  30. <context:annotation-config />
  31. <!-- 扫描注解web整合时用 -->
  32. <context:component-scan base-package="com.tp.soft.*" />
  33.  
  34. <bean id="jsonSerializer" class="com.tp.soft.base.redis.JsonRedisSeriaziler"/>
  35. <bean id="userDao" class="com.tp.soft.dao.impl.UserDaoImpl" />
  36. </beans>

2、配置公用Dao

AbstractBaseRedisDao.java

  1. package com.tp.soft.base.dao;
  2.  
  3. import java.io.Serializable;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.data.redis.serializer.RedisSerializer;
  8.  
  9. import com.tp.soft.base.redis.JsonRedisSeriaziler;
  10.  
  11. /**
  12. * @author taop
  13. *
  14. * @param <K>
  15. * @param <V>
  16. */
  17.  
  18. public abstract class AbstractBaseRedisDao<K extends Serializable, V extends Serializable> {
  19.  
  20. @Autowired
  21. protected RedisTemplate<K, V> redisTemplate;
  22.  
  23. //json转换时用 若用系统自带序列对象可不写
  24. @Autowired
  25. private JsonRedisSeriaziler jsonSerializer;
  26.  
  27. /**
  28. * 注入
  29. * 设置redisTemplate
  30. * @param redisTemplate
  31. */
  32. public void setRedisTemplate(RedisTemplate<K, V> redisTemplate){
  33. this.redisTemplate = redisTemplate;
  34. }
  35.  
  36. //json转换时用 若用系统自带序列对象可不写
  37. public void setJsonRedisSeriaziler(JsonRedisSeriaziler jsonSerializer) {
  38. this.jsonSerializer = jsonSerializer;
  39. }
  40.  
  41. //json转换时用 若用系统自带序列对象可不写
  42. protected String getRedisSerializer(Object obj){
  43. return jsonSerializer.seriazileAsString(obj);
  44. }
  45.  
  46. //json转换时用 若用系统自带序列对象可不写
  47. protected <T> T deserRedisSerializer(String str, Class<T> clazz){
  48. return jsonSerializer.deserializeAsObject(str, clazz);
  49. }
  50.  
  51. /**
  52. * 方法一
  53. * 获取 RedisSerializer
  54. * <br>------------------------------<br>
  55. */
  56. protected RedisSerializer<String> getRedisSerializer() {
  57. return redisTemplate.getStringSerializer();
  58. }
  59. }

3、若调用jackson 序列化对象 则新建, 若默认序列化对象可不创建

JsonRedisSeriaziler.java

  1. package com.tp.soft.base.redis;
  2.  
  3. import java.nio.charset.Charset;
  4.  
  5. import org.apache.commons.lang.SerializationException;
  6. import org.codehaus.jackson.map.ObjectMapper;
  7.  
  8. public class JsonRedisSeriaziler {
  9. public static final String EMPTY_JSON = "{}";
  10.  
  11. public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  12.  
  13. protected ObjectMapper objectMapper = new ObjectMapper();
  14. public JsonRedisSeriaziler(){}
  15.  
  16. /**
  17. * java-object as json-string
  18. * @param object
  19. * @return
  20. */
  21. public String seriazileAsString(Object object){
  22. if (object== null) {
  23. return EMPTY_JSON;
  24. }
  25. try {
  26. return this.objectMapper.writeValueAsString(object);
  27. } catch (Exception ex) {
  28. throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
  29. }
  30. }
  31.  
  32. /**
  33. * json-string to java-object
  34. * @param str
  35. * @return
  36. */
  37. public <T> T deserializeAsObject(String str,Class<T> clazz){
  38. if(str == null || clazz == null){
  39. return null;
  40. }
  41. try{
  42. return this.objectMapper.readValue(str, clazz);
  43. }catch (Exception ex) {
  44. throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
  45. }
  46. }
  47. }

4、实体类

AuUser.java

  1. package com.tp.soft.entity;
  2.  
  3. import java.io.Serializable;
  4.  
  5. public class AuUser implements Serializable{
  6.  
  7. /**
  8. *
  9. */
  10. private static final long serialVersionUID = -1695973853274402680L;
  11.  
  12. private String id;
  13.  
  14. private String username;
  15.  
  16. private String password;
  17.  
  18. public AuUser() {
  19.  
  20. }
  21.  
  22. public AuUser(String id, String username, String password) {
  23. super();
  24. this.id = id;
  25. this.username = username;
  26. this.password = password;
  27. }
  28.  
  29. public String getId() {
  30. return id;
  31. }
  32.  
  33. public void setId(String id) {
  34. this.id = id;
  35. }
  36.  
  37. public String getUsername() {
  38. return username;
  39. }
  40.  
  41. public void setUsername(String username) {
  42. this.username = username;
  43. }
  44.  
  45. public String getPassword() {
  46. return password;
  47. }
  48.  
  49. public void setPassword(String password) {
  50. this.password = password;
  51. }
  52.  
  53. }

5、接口

UserDao.java

  1. package com.tp.soft.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.tp.soft.entity.AuUser;
  6.  
  7. public interface UserDao {
  8. boolean add(AuUser auUser) ;
  9. boolean add(List<AuUser> list);
  10. void delete(String key);
  11. void delete(List<String> keys);
  12. boolean update(AuUser auUser);
  13. AuUser get(String keyId);
  14. }

6、接口实现类

UserDaoImpl.java

  1. package com.tp.soft.dao.impl;
  2.  
  3. import java.io.Serializable;
  4. import java.util.List;
  5.  
  6. import org.springframework.dao.DataAccessException;
  7. import org.springframework.data.redis.connection.RedisConnection;
  8. import org.springframework.data.redis.core.BoundValueOperations;
  9. import org.springframework.data.redis.core.RedisCallback;
  10. import org.springframework.data.redis.core.ValueOperations;
  11. import org.springframework.data.redis.serializer.RedisSerializer;
  12.  
  13. import com.tp.soft.base.dao.AbstractBaseRedisDao;
  14. import com.tp.soft.dao.UserDao;
  15. import com.tp.soft.entity.AuUser;
  16.  
  17. public class UserDaoImpl extends AbstractBaseRedisDao<String, AuUser> implements UserDao{
  18.  
  19. @Override
  20. public boolean add(final AuUser auUser) {
  21. // this.redisTemplate.opsForValue().set("pwd", "123456");
  22. // ValueOperations<String, String> operations = redisTemplate
  23. // .opsForValue();
  24. // String redisSerializer = getRedisSerializer(auUser);
  25. // operations.set("user:"+auUser.getId(), redisSerializer);
  26. // return true;
  27.  
  28. //方法一
  29. // redisTemplate.execute(new RedisCallback<Object>() {
  30. // public Object doInRedis(RedisConnection connection)
  31. // throws DataAccessException {
  32. // RedisSerializer<String> serializer = getRedisSerializer();
  33. // byte[] key = serializer.serialize(auUser.getId());
  34. // byte[] name = serializer.serialize(auUser.getUsername());
  35. // connection.set(key, name);
  36. // return null;
  37. // }
  38. // });
  39.  
  40. //方法二
  41. ValueOperations<String, AuUser> valueOps = redisTemplate.opsForValue();
  42. valueOps.set(auUser.getId(), auUser);
  43.  
  44. return true;
  45. }
  46.  
  47. @Override
  48. public AuUser get(final String keyId) {
  49. //System.out.println(this.redisTemplate.opsForValue().get("pwd"));
  50. // ValueOperations<String, String> operations = redisTemplate
  51. // .opsForValue();
  52. // String json = operations.get("user:"+keyId);
  53. // return deserRedisSerializer(json, AuUser.class);
  54. //return null;
  55.  
  56. //方法一
  57. /*AuUser result = redisTemplate.execute(new RedisCallback<AuUser>() {
  58. public AuUser doInRedis(RedisConnection connection)
  59. throws DataAccessException {
  60. RedisSerializer<String> serializer = getRedisSerializer();
  61. byte[] key = serializer.serialize(keyId);
  62. byte[] value = connection.get(key);
  63. if (value == null) {
  64. return null;
  65. }
  66. String nickname = serializer.deserialize(value);
  67. return new AuUser(keyId, nickname, "1234");
  68. }
  69. });
  70. return result; */
  71.  
  72. //方式2:不在redistemplate中配置Serializer,而是在Service的实现类中单独指定Serializer。
  73. BoundValueOperations<String, AuUser> boundValueOps = redisTemplate.boundValueOps(keyId);
  74. AuUser user = (AuUser) boundValueOps.get();
  75. return user;
  76. }
  77.  
  78. @Override
  79. public boolean add(List<AuUser> list) {
  80. // TODO Auto-generated method stub
  81. return false;
  82. }
  83.  
  84. @Override
  85. public void delete(String key) {
  86. // TODO Auto-generated method stub
  87.  
  88. }
  89.  
  90. @Override
  91. public void delete(List<String> keys) {
  92. // TODO Auto-generated method stub
  93.  
  94. }
  95.  
  96. @Override
  97. public boolean update(AuUser auUser) {
  98. // TODO Auto-generated method stub
  99. return false;
  100. }
  101. }

6、junit测试类

RedisZhTest.java

  1. package junit;
  2.  
  3. import junit.framework.Assert;
  4.  
  5. import org.junit.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.test.context.ContextConfiguration;
  8. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
  9.  
  10. import com.tp.soft.dao.UserDao;
  11. import com.tp.soft.entity.AuUser;
  12.  
  13. @ContextConfiguration(locations = {"classpath:/resource/spring-*.xml"})
  14. public class RedisZhTest extends AbstractJUnit4SpringContextTests{
  15. @Autowired
  16. private UserDao userDao;
  17.  
  18. @Test
  19. public void testAddUser(){
  20. AuUser user = new AuUser();
  21. user.setId("1");
  22. user.setUsername("taop");
  23. user.setPassword("12345");
  24. boolean result = userDao.add(user);
  25. //Assert.assertTrue(result);
  26. AuUser auUser = userDao.get("1");
  27. System.out.println(auUser.getUsername());
  28. System.out.println(auUser.getPassword());
  29. }
  30. }

结果打印:

redis+spring 整合的更多相关文章

  1. spring和redis的整合

    spring和redis的整合-超越昨天的自己系列(7) 超越昨天的自己系列(7) 扯淡:  最近一直在慢慢多学习各个组件,自己搭建出一些想法.是一个涉猎的过程,慢慢意识到知识是可以融汇贯通,举一反三 ...

  2. Redis和Spring整合

    Redis和Spring整合 Redis在这篇里就不做介绍了~以后系统的学学,然后整理写出来. 首先是环境的搭建 通过自己引包的方式,将redis和spring-redis的包引到自己的项目中,我项目 ...

  3. redis集群配置,spring整合jedis,缓存同步

    前台的商品数据(图片等加载缓慢)查询,先从redis缓存查询数据. redis是一个nosql数据库,内存版数据库,读取速度11w/s.本身具有内存淘汰机制,是单线程服务器(分时操作系统),线程安全. ...

  4. 【Spring】17、spring cache 与redis缓存整合

    spring cache,基本能够满足一般应用对缓存的需求,但现实总是很复杂,当你的用户量上去或者性能跟不上,总需要进行扩展,这个时候你或许对其提供的内存缓存不满意了,因为其不支持高可用性,也不具备持 ...

  5. 网站性能优化小结和spring整合redis

    现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...

  6. Spring整合Redis&JSON序列化&Spring/Web项目部署相关

    几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...

  7. spring整合redis之hello

    1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ...

  8. Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object

    我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!

  9. Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结

    Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结 这两天闲着没事想利用**Spring Boot**加上阿里的开源数据连接池**Druid* ...

随机推荐

  1. Spring Boot事务管理(下)

    在上两篇 Spring Boot事务管理(上)和Spring Boot事务管理(中)的基础上介绍注解@Transactional. 5 @Transactional属性 属性 类型 描述 value ...

  2. 从光盘安装ubuntu系统

    参考博客: https://www.jianshu.com/p/7929e4911206

  3. python练习题-day12

    用列表推导式做下列小题 (1) 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母 lst1=["admhdja","aksaudj","fh&q ...

  4. 代码中特殊的注释技术——TODO、FIXME和XXX的用处(转)

    1.声明 本篇转自博客:http://blog.csdn.net/reille/ 2.转载内容 2.1.前言 今天在阅读 Qt Creator 的源代码时,发现一些注释中有 FIXME 英文单词,用英 ...

  5. 如何使用Shell判断版本号的大小

    如果你想通过shell来比较两个版本号字符串,比如两个版本号1.1.2和1.2.1这两个版本谁是比较新的. 最简单的就是使用sort命令.加上参数"-V"后sort命令就可以把文本 ...

  6. vue中使用scss

    之前项目里我一般是使用less的,朋友问到如何引入scss,于是我就简单的跑了一下,以下主要供自己学习,如有更好的方法可以一起交流讨论一下 第一步,安装依赖 cnpm install node-sas ...

  7. PHP----------用curl方式请求接口在同一个项目里面的时候不能请求的情况

    1.环境是wnmp 2.NGINX中,看PHP文件块fastcig-pass的设置值(127.0.0.1:9000).设置都是以keepalive方式请求,接收到PHP文件时,交于后端过程PHPCGI ...

  8. Python记录13:软件开发目录规范

    软件开发目录规范 开发一个软件,一个工程项目,一般应该具备以下的几个基本的文件夹和模块,当然,这并不是一成不变的,根据项目的不同会有一定的差异,不过作为一个入门级的新手,建议暂时按照以下的规范编写: ...

  9. git之概念图

    1.git四大区. . 2. 3. 4.

  10. RxJava 详解——简洁的异步操作(二)

    上次说的两个例子,事件的发出和消费都是在同一个线程的.如果只用上面的方法,实现出来的只是一个同步的观察者模式.观察者模式本身的目的就是异步机制,因此异步对于 RxJava 是至关重要的.而要实现异步, ...