redis+spring 整合
最近在研究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/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/jee
- http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
- http://www.springframework.org/schema/jdbc
- http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
- http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
- http://cxf.apache.org/jaxws
- http://cxf.apache.org/schemas/jaxws.xsd
- http://cxf.apache.org/jaxrs
- http://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/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/jee
- http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
- http://www.springframework.org/schema/jdbc
- http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
- http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
- http://cxf.apache.org/jaxws
- http://cxf.apache.org/schemas/jaxws.xsd
- http://cxf.apache.org/jaxrs
- http://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> {
- @Autowired
- protected RedisTemplate<K, V> redisTemplate;
- //json转换时用 若用系统自带序列对象可不写
- @Autowired
- private 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{
- @Override
- public 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;
- }
- @Override
- public 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;
- }
- @Override
- public boolean add(List<AuUser> list) {
- // TODO Auto-generated method stub
- return false;
- }
- @Override
- public void delete(String key) {
- // TODO Auto-generated method stub
- }
- @Override
- public void delete(List<String> keys) {
- // TODO Auto-generated method stub
- }
- @Override
- public boolean update(AuUser auUser) {
- // TODO Auto-generated method stub
- return 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{
- @Autowired
- private UserDao userDao;
- @Test
- public 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());
- }
- }
结果打印:
redis+spring 整合的更多相关文章
- spring和redis的整合
spring和redis的整合-超越昨天的自己系列(7) 超越昨天的自己系列(7) 扯淡: 最近一直在慢慢多学习各个组件,自己搭建出一些想法.是一个涉猎的过程,慢慢意识到知识是可以融汇贯通,举一反三 ...
- Redis和Spring整合
Redis和Spring整合 Redis在这篇里就不做介绍了~以后系统的学学,然后整理写出来. 首先是环境的搭建 通过自己引包的方式,将redis和spring-redis的包引到自己的项目中,我项目 ...
- redis集群配置,spring整合jedis,缓存同步
前台的商品数据(图片等加载缓慢)查询,先从redis缓存查询数据. redis是一个nosql数据库,内存版数据库,读取速度11w/s.本身具有内存淘汰机制,是单线程服务器(分时操作系统),线程安全. ...
- 【Spring】17、spring cache 与redis缓存整合
spring cache,基本能够满足一般应用对缓存的需求,但现实总是很复杂,当你的用户量上去或者性能跟不上,总需要进行扩展,这个时候你或许对其提供的内存缓存不满意了,因为其不支持高可用性,也不具备持 ...
- 网站性能优化小结和spring整合redis
现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...
- Spring整合Redis&JSON序列化&Spring/Web项目部署相关
几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...
- spring整合redis之hello
1.pom.xml文件 <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.spri ...
- Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object
我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!
- Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结
Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结 这两天闲着没事想利用**Spring Boot**加上阿里的开源数据连接池**Druid* ...
随机推荐
- Spring Boot事务管理(下)
在上两篇 Spring Boot事务管理(上)和Spring Boot事务管理(中)的基础上介绍注解@Transactional. 5 @Transactional属性 属性 类型 描述 value ...
- 从光盘安装ubuntu系统
参考博客: https://www.jianshu.com/p/7929e4911206
- python练习题-day12
用列表推导式做下列小题 (1) 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母 lst1=["admhdja","aksaudj","fh&q ...
- 代码中特殊的注释技术——TODO、FIXME和XXX的用处(转)
1.声明 本篇转自博客:http://blog.csdn.net/reille/ 2.转载内容 2.1.前言 今天在阅读 Qt Creator 的源代码时,发现一些注释中有 FIXME 英文单词,用英 ...
- 如何使用Shell判断版本号的大小
如果你想通过shell来比较两个版本号字符串,比如两个版本号1.1.2和1.2.1这两个版本谁是比较新的. 最简单的就是使用sort命令.加上参数"-V"后sort命令就可以把文本 ...
- vue中使用scss
之前项目里我一般是使用less的,朋友问到如何引入scss,于是我就简单的跑了一下,以下主要供自己学习,如有更好的方法可以一起交流讨论一下 第一步,安装依赖 cnpm install node-sas ...
- PHP----------用curl方式请求接口在同一个项目里面的时候不能请求的情况
1.环境是wnmp 2.NGINX中,看PHP文件块fastcig-pass的设置值(127.0.0.1:9000).设置都是以keepalive方式请求,接收到PHP文件时,交于后端过程PHPCGI ...
- Python记录13:软件开发目录规范
软件开发目录规范 开发一个软件,一个工程项目,一般应该具备以下的几个基本的文件夹和模块,当然,这并不是一成不变的,根据项目的不同会有一定的差异,不过作为一个入门级的新手,建议暂时按照以下的规范编写: ...
- git之概念图
1.git四大区. . 2. 3. 4.
- RxJava 详解——简洁的异步操作(二)
上次说的两个例子,事件的发出和消费都是在同一个线程的.如果只用上面的方法,实现出来的只是一个同步的观察者模式.观察者模式本身的目的就是异步机制,因此异步对于 RxJava 是至关重要的.而要实现异步, ...