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

结构图:

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

接下来开始配置项目:

1、配置文件

redis.properties

redis.host = 192.168.76.76
redis.port = 6379
redis.pass = admin
redis.maxIdle = 200
redis.maxActive = 1024
redis.maxWait = 10000
redis.testOnBorrow = true

spring-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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:cache="http://www.springframework.org/schema/cache"xmlns:jaxws="http://cxf.apache.org/jaxws"xmlns:jaxrs="http://cxf.apache.org/jaxrs"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-3.1.xsdhttp://www.springframework.org/schema/jdbchttp://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd http://cxf.apache.org/jaxwshttp://cxf.apache.org/schemas/jaxws.xsdhttp://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd"  default-autowire="byName" ><!-- 引入配置文件 --><context:property-placeholder location="classpath:/resource/redis.properties"/><!-- 连接池基本参数配置,类似数据库连接池 --><bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="maxIdle" value="${redis.maxIdle}" /><property name="testOnBorrow" value="${redis.testOnBorrow}"/></bean><!-- 连接池配置,类似数据库连接池 --><bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" ><property name="hostName" value="${redis.host}"></property><property name="port" value="${redis.port}"></property><property name="password" value="${redis.pass}"></property><property name="poolConfig"  ref="poolConfig"></property> </bean><!-- 调用连接池工厂配置 --><bean id="redisTemplate" class=" org.springframework.data.redis.core.RedisTemplate"><property name="connectionFactory" ref="connectionFactory"></property><!-- 自定义json序列化存储 --><!--  <property name="defaultSerializer">  <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>  </property>   --><!-- 如果不配置Serializer,那么存储的时候智能使用String,如果用User类型存储,那么会提示错误User can't cast   to String!!! -->  <property name="keySerializer">  <bean  class="org.springframework.data.redis.serializer.StringRedisSerializer" />  </property>  <property name="valueSerializer">  <bean  class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  </property> </bean>
</beans>

spring-source.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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:cache="http://www.springframework.org/schema/cache"xmlns:jaxws="http://cxf.apache.org/jaxws"xmlns:jaxrs="http://cxf.apache.org/jaxrs"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-3.1.xsdhttp://www.springframework.org/schema/jdbchttp://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd http://cxf.apache.org/jaxwshttp://cxf.apache.org/schemas/jaxws.xsdhttp://cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd"  default-autowire="byName" ><context:annotation-config /><!-- 扫描注解web整合时用 --><context:component-scan base-package="com.tp.soft.*" /><bean id="jsonSerializer" class="com.tp.soft.base.redis.JsonRedisSeriaziler"/>  <bean id="userDao" class="com.tp.soft.dao.impl.UserDaoImpl" />
</beans>

2、配置公用Dao

AbstractBaseRedisDao.java

package com.tp.soft.base.dao;import java.io.Serializable;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;import com.tp.soft.base.redis.JsonRedisSeriaziler;/*** @author taop** @param <K>* @param <V>*/public abstract class AbstractBaseRedisDao<K extends Serializable, V extends Serializable> {@Autowiredprotected RedisTemplate<K, V> redisTemplate;//json转换时用 若用系统自带序列对象可不写
    @Autowiredprivate JsonRedisSeriaziler jsonSerializer;/*** 注入* 设置redisTemplate* @param redisTemplate*/public void setRedisTemplate(RedisTemplate<K, V> redisTemplate){this.redisTemplate = redisTemplate;}//json转换时用 若用系统自带序列对象可不写public void setJsonRedisSeriaziler(JsonRedisSeriaziler jsonSerializer) {this.jsonSerializer = jsonSerializer;}//json转换时用 若用系统自带序列对象可不写protected String getRedisSerializer(Object obj){return jsonSerializer.seriazileAsString(obj);}//json转换时用 若用系统自带序列对象可不写protected <T> T deserRedisSerializer(String str, Class<T> clazz){return jsonSerializer.deserializeAsObject(str, clazz);}/*** 方法一* 获取 RedisSerializer* <br>------------------------------<br>*/ protected RedisSerializer<String> getRedisSerializer() { return redisTemplate.getStringSerializer(); }
}

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

JsonRedisSeriaziler.java

package com.tp.soft.base.redis;import java.nio.charset.Charset;import org.apache.commons.lang.SerializationException;
import org.codehaus.jackson.map.ObjectMapper;public class JsonRedisSeriaziler {public static final String EMPTY_JSON = "{}";  public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");  protected ObjectMapper objectMapper = new ObjectMapper();  public JsonRedisSeriaziler(){}  /** * java-object as json-string * @param object * @return */  public String seriazileAsString(Object object){  if (object== null) {  return EMPTY_JSON;  }  try {  return this.objectMapper.writeValueAsString(object);  } catch (Exception ex) {  throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);  }  }  /** * json-string to java-object * @param str * @return */  public <T> T deserializeAsObject(String str,Class<T> clazz){  if(str == null || clazz == null){  return null;  }  try{  return this.objectMapper.readValue(str, clazz);  }catch (Exception ex) {  throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);  }  }
}

4、实体类

AuUser.java

package com.tp.soft.entity;import java.io.Serializable;public class AuUser implements Serializable{/*** */private static final long serialVersionUID = -1695973853274402680L;private String id;private String username;private String password;public AuUser() {}public AuUser(String id, String username, String password) {super();this.id = id;this.username = username;this.password = password;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}

5、接口

UserDao.java

package com.tp.soft.dao;import java.util.List;import com.tp.soft.entity.AuUser;public interface UserDao {boolean add(AuUser auUser) ;boolean add(List<AuUser> list);void delete(String key);void delete(List<String> keys);boolean update(AuUser auUser);AuUser get(String keyId);
}

6、接口实现类

UserDaoImpl.java

package com.tp.soft.dao.impl;import java.io.Serializable;
import java.util.List;import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;import com.tp.soft.base.dao.AbstractBaseRedisDao;
import com.tp.soft.dao.UserDao;
import com.tp.soft.entity.AuUser;public class UserDaoImpl extends AbstractBaseRedisDao<String, AuUser> implements UserDao{@Overridepublic boolean add(final AuUser auUser) {
//         this.redisTemplate.opsForValue().set("pwd", "123456");
//         ValueOperations<String, String> operations = redisTemplate
//                .opsForValue();
//         String redisSerializer = getRedisSerializer(auUser);
//         operations.set("user:"+auUser.getId(), redisSerializer);
//         return true;//方法一
//        redisTemplate.execute(new RedisCallback<Object>() {
//            public Object doInRedis(RedisConnection connection)
//                    throws DataAccessException {
//                RedisSerializer<String> serializer = getRedisSerializer();
//                byte[] key  = serializer.serialize(auUser.getId());
//                byte[] name = serializer.serialize(auUser.getUsername());
//                connection.set(key, name);
//                return null;
//              }
//        }); //方法二ValueOperations<String, AuUser> valueOps = redisTemplate.opsForValue();  valueOps.set(auUser.getId(), auUser);return true;}@Overridepublic AuUser get(final String keyId) {//System.out.println(this.redisTemplate.opsForValue().get("pwd"));
//        ValueOperations<String, String> operations = redisTemplate
//                .opsForValue();
//        String json = operations.get("user:"+keyId);
//        return deserRedisSerializer(json, AuUser.class);//return null;//方法一/*AuUser result = redisTemplate.execute(new RedisCallback<AuUser>() { public AuUser doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(keyId); byte[] value = connection.get(key); if (value == null) { return null; } String nickname = serializer.deserialize(value); return new AuUser(keyId, nickname, "1234"); } }); return result; *///方式2:不在redistemplate中配置Serializer,而是在Service的实现类中单独指定Serializer。  BoundValueOperations<String, AuUser> boundValueOps = redisTemplate.boundValueOps(keyId);  AuUser user = (AuUser) boundValueOps.get();  return user;  }@Overridepublic boolean add(List<AuUser> list) {// TODO Auto-generated method stubreturn false;}@Overridepublic void delete(String key) {// TODO Auto-generated method stub
        }@Overridepublic void delete(List<String> keys) {// TODO Auto-generated method stub
        }@Overridepublic boolean update(AuUser auUser) {// TODO Auto-generated method stubreturn false;}
}

6、junit测试类

RedisZhTest.java

package junit;import junit.framework.Assert;import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;import com.tp.soft.dao.UserDao;
import com.tp.soft.entity.AuUser;@ContextConfiguration(locations = {"classpath:/resource/spring-*.xml"})
public class RedisZhTest extends AbstractJUnit4SpringContextTests{@Autowiredprivate UserDao userDao;@Testpublic void testAddUser(){AuUser user = new AuUser();user.setId("1");user.setUsername("taop");user.setPassword("12345");boolean result = userDao.add(user);//Assert.assertTrue(result);AuUser auUser = userDao.get("1");System.out.println(auUser.getUsername());System.out.println(auUser.getPassword());}
}

结果打印:

转载于:https://www.cnblogs.com/tplovejava/p/7130787.html

redis+spring 整合相关推荐

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

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

  2. redis入门——Spring整合篇

    redis入门--Spring整合篇 @(Redis)[服务器, 连接池, 集群, jedis, spring] redis入门Spring整合篇 Spring整合Redis redis整合分析 编写 ...

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

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

  4. can not load key value key was removed or redis-server went away 关于spring 整合redis 以及保存到redis

    spring 整合redis 1. 引用依赖 <!--Redis--> <dependency><groupId>org.springframework.boot& ...

  5. 不要再找了,Java操作Redis、Spring整合Redis及SpringBoot整合Redis这里都有

    文章开始之前先抛出一个问题:Jedis.Lettuce.Redisson以及RedisTemplate几者之间有什么区别,又有什么联系? 如果你心中已经很清晰的有了答案,那么本文你可以很轻松的阅读过去 ...

  6. redis -Spring与Jedis集群 Sentinel

    2019独角兽企业重金招聘Python工程师标准>>> redis -Spring与Jedis集群 Sentinel 博客分类: 缓存 首先不得不服Spring这个宇宙无敌的开源框架 ...

  7. ssh项目实战----Spring计时器任务 Spring整合JavaMail(邮件发送)

    一.常用数据频度维护 对于系统使用度较高的数据,客户在查看时希望这些数据最好先出现,此时需要为其添加排序规则.在进行排序时,使用次数成为排序的依据.因此需要设置一个字段用来描述某种数据的使用次数,也就 ...

  8. 【struts2+hibernate+spring项目实战】Spring计时器任务 Spring整合JavaMail(邮件发送)(ssh)

    一.常用数据频度维护 对于系统使用度较高的数据,客户在查看时希望这些数据最好先出现,此时需要为其添加排序规则.在进行排序时,使用次数成为排序的依据.因此需要设置一个字段用来描述某种数据的使用次数,也就 ...

  9. 缓存redis的整合

    reids的整合过程 1 引入pom依赖信息(本工程所有redis统一放入service-util) <dependency><groupId>redis.clients< ...

最新文章

  1. .NET业务实体类验证组件Fluent Validation
  2. 大学哪些专业要学python_非计算机专业的大学生是否有必要学习Python编程
  3. QT的QDomDocument类的使用
  4. 高效运维最佳实践:如何做好On-call和事故响应?
  5. 简单了解RestTemplate源码
  6. 介绍Pro*c编程的经验
  7. python找图里的环_python判断无向图环是否存在的示例
  8. 动词ing基本用法_如果实在分不清英语动名词和现在分词,那就直接学习-ing分词...
  9. 2021年财富世界500强,苹果是全球最赚钱公司,小米第338位,第一是它
  10. java零碎要点013---java 根据“|”分割字符串需要使用“\\|” 双反斜杠做特殊处理
  11. unigui发展路线图
  12. Java单例模式实现(线程安全)
  13. 手把手教你在Windows下搭建React Native Android开发环境
  14. 数据挖掘案例分析(1)-Apriori算法
  15. 一文掌握智能抠图Deep Image Matting(pytorch实现)
  16. C 中用语言描述出下述方法的功能,2015年10月自考《大学语文》模拟试题及答案4...
  17. petalinux(3)——创建APP
  18. 如何炸掉……呃,月球?
  19. 使用Echars实现水滴状、环形图、分割图、堆叠、组织架构图、地图轮廓等图表
  20. Spring框架基础学习小结。概念,文件配置

热门文章

  1. 945928-17-6,TAMRA alkyne,5-Carboxytetramethylrhodamine-Alkyne,5-羧基四甲基罗丹明-炔烃
  2. 完美解决前端无法上传大文件方法
  3. java实现手动派单,一种智能并单及派单方法与流程
  4. python定时替换文件内容
  5. 雅思英语作文计算机和历史,关于computer的雅思写作范文
  6. 海康威视网络摄像头购买指南(焦距像素等参数)
  7. 深入剖析DHCP服务IP地址自动分配原理
  8. [HCTF 2018] WarmUp
  9. 根域名服务器的一点理解
  10. 解决(‘You must install pydot (`pip install pydot`) and install graphviz (see...) ‘, ‘for plot_model..