Spring 整合 Redis
http://blog.csdn.net/java2000_wl/article/details/8543203/
pom构建:
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.x.redis</groupId>
- <artifactId>springredis</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <dependencies>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-redis</artifactId>
- <version>1.0.2.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>3.1.2.RELEASE</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>2.1.0</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.8.2</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
spring配置文件(applicationContext.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:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <context:property-placeholder location="classpath:redis.properties" />
- <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
- <property name="maxIdle" value="${redis.maxIdle}" />
- <property name="maxActive" value="${redis.maxActive}" />
- <property name="maxWait" value="${redis.maxWait}" />
- <property name="testOnBorrow" value="${redis.testOnBorrow}" />
- </bean>
- <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
- p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
- <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
- <property name="connectionFactory" ref="connectionFactory" />
- </bean>
- <bean id="userDao" class="com.x.dao.impl.UserDao" />
- </beans>
redis.properties
- # Redis settings
- redis.host=localhost
- redis.port=6379
- redis.pass=java2000_wl
- redis.maxIdle=300
- redis.maxActive=600
- redis.maxWait=1000
- redis.testOnBorrow=true
Java代码:
- package com.x.entity;
- import java.io.Serializable;
- /**
- * @author http://blog.csdn.net/java2000_wl
- * @version <b>1.0</b>
- */
- public class User implements Serializable {
- private static final long serialVersionUID = -6011241820070393952L;
- private String id;
- private String name;
- private String password;
- /**
- * <br>------------------------------<br>
- */
- public User() {
- }
- /**
- * <br>------------------------------<br>
- */
- public User(String id, String name, String password) {
- super();
- this.id = id;
- this.name = name;
- this.password = password;
- }
- /**
- * 获得id
- * @return the id
- */
- public String getId() {
- return id;
- }
- /**
- * 设置id
- * @param id the id to set
- */
- public void setId(String id) {
- this.id = id;
- }
- /**
- * 获得name
- * @return the name
- */
- public String getName() {
- return name;
- }
- /**
- * 设置name
- * @param name the name to set
- */
- public void setName(String name) {
- this.name = name;
- }
- /**
- * 获得password
- * @return the password
- */
- public String getPassword() {
- return password;
- }
- /**
- * 设置password
- * @param password the password to set
- */
- public void setPassword(String password) {
- this.password = password;
- }
- }
- package com.x.dao;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.RedisSerializer;
- /**
- * AbstractBaseRedisDao
- * @author http://blog.csdn.net/java2000_wl
- * @version <b>1.0</b>
- */
- public abstract class AbstractBaseRedisDao<K, V> {
- @Autowired
- protected RedisTemplate<K, V> redisTemplate;
- /**
- * 设置redisTemplate
- * @param redisTemplate the redisTemplate to set
- */
- public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
- this.redisTemplate = redisTemplate;
- }
- /**
- * 获取 RedisSerializer
- * <br>------------------------------<br>
- */
- protected RedisSerializer<String> getRedisSerializer() {
- return redisTemplate.getStringSerializer();
- }
- }
- package com.x.dao;
- import java.util.List;
- import com.x.entity.User;
- /**
- * @author http://blog.csdn.net/java2000_wl
- * @version <b>1.0</b>
- */
- public interface IUserDao {
- /**
- * 新增
- * <br>------------------------------<br>
- * @param user
- * @return
- */
- boolean add(User user);
- /**
- * 批量新增 使用pipeline方式
- * <br>------------------------------<br>
- * @param list
- * @return
- */
- boolean add(List<User> list);
- /**
- * 删除
- * <br>------------------------------<br>
- * @param key
- */
- void delete(String key);
- /**
- * 删除多个
- * <br>------------------------------<br>
- * @param keys
- */
- void delete(List<String> keys);
- /**
- * 修改
- * <br>------------------------------<br>
- * @param user
- * @return
- */
- boolean update(User user);
- /**
- * 通过key获取
- * <br>------------------------------<br>
- * @param keyId
- * @return
- */
- User get(String keyId);
- }
- package com.x.dao.impl;
- import java.util.ArrayList;
- import java.util.List;
- import org.springframework.dao.DataAccessException;
- import org.springframework.data.redis.connection.RedisConnection;
- import org.springframework.data.redis.core.RedisCallback;
- import org.springframework.data.redis.serializer.RedisSerializer;
- import org.springframework.util.Assert;
- import com.x.dao.AbstractBaseRedisDao;
- import com.x.dao.IUserDao;
- import com.x.entity.User;
- /**
- * Dao
- * @author http://blog.csdn.net/java2000_wl
- * @version <b>1.0</b>
- */
- public class UserDao extends AbstractBaseRedisDao<String, User> implements IUserDao {
- /**
- * 新增
- *<br>------------------------------<br>
- * @param user
- * @return
- */
- public boolean add(final User user) {
- boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
- public Boolean doInRedis(RedisConnection connection)
- throws DataAccessException {
- RedisSerializer<String> serializer = getRedisSerializer();
- byte[] key = serializer.serialize(user.getId());
- byte[] name = serializer.serialize(user.getName());
- return connection.setNX(key, name);
- }
- });
- return result;
- }
- /**
- * 批量新增 使用pipeline方式
- *<br>------------------------------<br>
- *@param list
- *@return
- */
- public boolean add(final List<User> list) {
- Assert.notEmpty(list);
- boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
- public Boolean doInRedis(RedisConnection connection)
- throws DataAccessException {
- RedisSerializer<String> serializer = getRedisSerializer();
- for (User user : list) {
- byte[] key = serializer.serialize(user.getId());
- byte[] name = serializer.serialize(user.getName());
- connection.setNX(key, name);
- }
- return true;
- }
- }, false, true);
- return result;
- }
- /**
- * 删除
- * <br>------------------------------<br>
- * @param key
- */
- public void delete(String key) {
- List<String> list = new ArrayList<String>();
- list.add(key);
- delete(list);
- }
- /**
- * 删除多个
- * <br>------------------------------<br>
- * @param keys
- */
- public void delete(List<String> keys) {
- redisTemplate.delete(keys);
- }
- /**
- * 修改
- * <br>------------------------------<br>
- * @param user
- * @return
- */
- public boolean update(final User user) {
- String key = user.getId();
- if (get(key) == null) {
- throw new NullPointerException("数据行不存在, key = " + key);
- }
- boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
- public Boolean doInRedis(RedisConnection connection)
- throws DataAccessException {
- RedisSerializer<String> serializer = getRedisSerializer();
- byte[] key = serializer.serialize(user.getId());
- byte[] name = serializer.serialize(user.getName());
- connection.set(key, name);
- return true;
- }
- });
- return result;
- }
- /**
- * 通过key获取
- * <br>------------------------------<br>
- * @param keyId
- * @return
- */
- public User get(final String keyId) {
- User result = redisTemplate.execute(new RedisCallback<User>() {
- public User 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 name = serializer.deserialize(value);
- return new User(keyId, name, null);
- }
- });
- return result;
- }
- }
- import java.util.ArrayList;
- import java.util.List;
- 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.x.dao.IUserDao;
- import com.x.entity.User;
- /**
- * 测试
- * @author http://blog.csdn.net/java2000_wl
- * @version <b>1.0</b>
- */
- @ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
- public class RedisTest extends AbstractJUnit4SpringContextTests {
- @Autowired
- private IUserDao userDao;
- /**
- * 新增
- * <br>------------------------------<br>
- */
- @Test
- public void testAddUser() {
- User user = new User();
- user.setId("user1");
- user.setName("java2000_wl");
- boolean result = userDao.add(user);
- Assert.assertTrue(result);
- }
- /**
- * 批量新增 普通方式
- * <br>------------------------------<br>
- */
- @Test
- public void testAddUsers1() {
- List<User> list = new ArrayList<User>();
- for (int i = 10; i < 50000; i++) {
- User user = new User();
- user.setId("user" + i);
- user.setName("java2000_wl" + i);
- list.add(user);
- }
- long begin = System.currentTimeMillis();
- for (User user : list) {
- userDao.add(user);
- }
- System.out.println(System.currentTimeMillis() - begin);
- }
- /**
- * 批量新增 pipeline方式
- * <br>------------------------------<br>
- */
- @Test
- public void testAddUsers2() {
- List<User> list = new ArrayList<User>();
- for (int i = 10; i < 1500000; i++) {
- User user = new User();
- user.setId("user" + i);
- user.setName("java2000_wl" + i);
- list.add(user);
- }
- long begin = System.currentTimeMillis();
- boolean result = userDao.add(list);
- System.out.println(System.currentTimeMillis() - begin);
- Assert.assertTrue(result);
- }
- /**
- * 修改
- * <br>------------------------------<br>
- */
- @Test
- public void testUpdate() {
- User user = new User();
- user.setId("user1");
- user.setName("new_password");
- boolean result = userDao.update(user);
- Assert.assertTrue(result);
- }
- /**
- * 通过key删除单个
- * <br>------------------------------<br>
- */
- @Test
- public void testDelete() {
- String key = "user1";
- userDao.delete(key);
- }
- /**
- * 批量删除
- * <br>------------------------------<br>
- */
- @Test
- public void testDeletes() {
- List<String> list = new ArrayList<String>();
- for (int i = 0; i < 10; i++) {
- list.add("user" + i);
- }
- userDao.delete(list);
- }
- /**
- * 获取
- * <br>------------------------------<br>
- */
- @Test
- public void testGetUser() {
- String id = "user1";
- User user = userDao.get(id);
- Assert.assertNotNull(user);
- Assert.assertEquals(user.getName(), "java2000_wl");
- }
- /**
- * 设置userDao
- * @param userDao the userDao to set
- */
- public void setUserDao(IUserDao userDao) {
- this.userDao = userDao;
- }
- }
Spring 整合 Redis的更多相关文章
- 网站性能优化小结和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的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!
- Redis的安装以及spring整合Redis时出现Could not get a resource from the pool
Redis的下载与安装 在Linux上使用wget http://download.redis.io/releases/redis-5.0.0.tar.gz下载源码到指定位置 解压:tar -xvf ...
- Spring整合redis实现key过期事件监听
打开redis服务的配置文件 添加notify-keyspace-events Ex 如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ...
- (转)Spring整合Redis作为缓存
采用Redis作为Web系统的缓存.用Spring的Cache整合Redis. 一.关于redis的相关xml文件的写法 <?xml version="1.0" ...
- spring整合redis使用RedisTemplate的坑Could not get a resource from the pool
一.背景 项目中使用spring框架整合redis,使用框架封装的RedisTemplate来实现数据的增删改查,项目上线后,我发现运行一段时间后,会出现异常Could not get a resou ...
- Spring整合redis,通过sentinel进行主从切换
实现功能描述: redis服务器进行Master-slaver-slaver-....主从配置,通过2台sentinel进行failOver故障转移,自动切换,采用该代码完全可以直接用于实际生产环境. ...
- SpringBoot开发二十-Redis入门以及Spring整合Redis
安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis. 代码实现 Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个 Redis 的常用命 ...
随机推荐
- java 线程安全 Lock
java.util.concurrent.locks 对于线程安全我们前面使用了synchronized关键字,对于线程的协作我们使用Object.wait()和Object.notify().在JD ...
- 用例设计工具PICT — 输入组合覆盖
1 成对测试简介 成对测试(Pairwise Testing)又称结对测试.两两测试,是一种正交分析的测试技术.成对组合覆盖这一概念是Mandl于1985年在测试Aad编译程序时提出来的.是当不可能遍 ...
- 自定义Image自动切换图像控件
做这么一个控件,图片自动切换,形成动画效果. 随便的码码,码完发现东西太少了,不过还算完善. public class MyPictureBox : PictureBox { Timer timer ...
- JS原生第四篇 (帅哥)
1.1 1. 循环 for(初始化; 退出条件; 增量) { } while(退出条件) { } do { 语句 } while(退出条件) 2. switch( ) 多选1 ...
- CSS3新技能学习笔记
说来惭愧自认为对css了解,但在项目中却很少有正确的使用css,如果面向对象的css吧,其实也不是不想用而是css天生就是面向对象的,高度可重用,但是如果把每个都单独提取,难免会有过多的class以及 ...
- ZooKeeper官方文档翻译——ZooKeeper Overview 3.4.6
ZooKeeper ZooKeeper: A Distributed Coordination Service for Distributed Applications (针对分布式应用的分布式调度服 ...
- 使用Javascript监控前端相关数据
项目开发完成外发后,没有一个监控系统,我们很难了解到发布出去的代码在用户机器上执行是否正确,所以需要建立前端代码性能相关的监控系统. 所以我们需要做以下的一些模块: 一.收集脚本执行错误 functi ...
- [转载]Office Visio快捷键
“帮助”任务窗格和“帮助”窗口 使用“帮助”任务窗格和“帮助”窗口 通过“帮助”任务窗格,您可以访问“Microsoft Office Visio 帮助”的全部内容,该窗格显示为 Microsoft ...
- Spark入门实战系列--9.Spark图计算GraphX介绍及实例
[注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .GraphX介绍 1.1 GraphX应用背景 Spark GraphX是一个分布式图处理 ...
- 【Android】Android Studio 进行代码混淆,打包release APK
整了一天,感觉坑挺多. 1. 选择如图中的选项Android Studio进行签名打包: 2. 填写APP对应的信息:(最好用个文本记下来放在项目中同步给Team) - Key store path: ...