redis和spring整合

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: pom构建: [html] view plain copy  print? <modelVersion>4.0.0</modelVersion>   <groupId>com.x.redis</groupId>   <artifactId>springredis&l

pom构建:

[html]  view plain  copy
 print ?
  1. <modelVersion>4.0.0</modelVersion>  
  2. <groupId>com.x.redis</groupId>  
  3. <artifactId>springredis</artifactId>  
  4. <version>0.0.1-SNAPSHOT</version>  
  5.   
  6. <dependencies>  
  7.     <dependency>  
  8.         <groupId>org.springframework.data</groupId>  
  9.         <artifactId>spring-data-redis</artifactId>  
  10.         <version>1.0.2.RELEASE</version>  
  11.     </dependency>  
  12.     <dependency>  
  13.         <groupId>org.springframework</groupId>  
  14.         <artifactId>spring-test</artifactId>  
  15.         <version>3.1.2.RELEASE</version>  
  16.         <scope>test</scope>  
  17.     </dependency>  
  18.       
  19.     <dependency>  
  20.         <groupId>redis.clients</groupId>  
  21.         <artifactId>jedis</artifactId>  
  22.         <version>2.1.0</version>  
  23.     </dependency>  
  24.       
  25.      <dependency>  
  26.         <groupId>junit</groupId>  
  27.         <artifactId>junit</artifactId>  
  28.         <version>4.8.2</version>  
  29.         <scope>test</scope>  
  30.     </dependency>  
  31. </dependencies>  

spring配置文件(applicationContext.xml):

[html]  view plain  copy
 print ?
  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" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:aop="http://www.springframework.org/schema/aop"  
  7.     xsi:schemaLocation="  
  8.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
  10.   
  11.     <context:property-placeholder location="classpath:redis.properties" />  
  12.   
  13.     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  14.         <property name="maxIdle" value="${redis.maxIdle}" />  
  15.         <property name="maxActive" value="${redis.maxActive}" />  
  16.         <property name="maxWait" value="${redis.maxWait}" />  
  17.         <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
  18.     </bean>  
  19.       
  20.     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
  21.         p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/>  
  22.       
  23.     <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  24.         <property name="connectionFactory"   ref="connectionFactory" />  
  25.     </bean>         
  26.       
  27.     <bean id="userDao" class="com.x.dao.impl.UserDao" />   
  28. </beans>  
redis.properties

[html]  view plain  copy
 print ?
  1. # Redis settings  
  2. redis.host=localhost  
  3. redis.port=6379  
  4. redis.pass=java2000_wl  
  5.   
  6.   
  7. redis.maxIdle=300  
  8. redis.maxActive=600  
  9. redis.maxWait=1000  
  10. redis.testOnBorrow=true  

java代码:

[java]  view plain  copy
 print ?
  1. package com.x.entity;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. /**  
  6.  * @author http://blog.csdn.net/java2000_wl  
  7.  * @version <b>1.0</b>  
  8.  */   
  9. public class User implements Serializable {  
  10.       
  11.     private static final long serialVersionUID = -6011241820070393952L;  
  12.   
  13.     private String id;  
  14.       
  15.     private String name;  
  16.       
  17.     private String password;  
  18.   
  19.     /** 
  20.      * <br>------------------------------<br> 
  21.      */  
  22.     public User() {  
  23.           
  24.     }  
  25.       
  26.     /** 
  27.      * <br>------------------------------<br> 
  28.      */  
  29.     public User(String id, String name, String password) {  
  30.         super();  
  31.         this.id = id;  
  32.         this.name = name;  
  33.         this.password = password;  
  34.     }  
  35.   
  36.     /** 
  37.      * 获得id 
  38.      * @return the id 
  39.      */  
  40.     public String getId() {  
  41.         return id;  
  42.     }  
  43.   
  44.     /** 
  45.      * 设置id 
  46.      * @param id the id to set 
  47.      */  
  48.     public void setId(String id) {  
  49.         this.id = id;  
  50.     }  
  51.   
  52.     /** 
  53.      * 获得name 
  54.      * @return the name 
  55.      */  
  56.     public String getName() {  
  57.         return name;  
  58.     }  
  59.   
  60.     /** 
  61.      * 设置name 
  62.      * @param name the name to set 
  63.      */  
  64.     public void setName(String name) {  
  65.         this.name = name;  
  66.     }  
  67.   
  68.     /** 
  69.      * 获得password 
  70.      * @return the password 
  71.      */  
  72.     public String getPassword() {  
  73.         return password;  
  74.     }  
  75.   
  76.     /** 
  77.      * 设置password 
  78.      * @param password the password to set 
  79.      */  
  80.     public void setPassword(String password) {  
  81.         this.password = password;  
  82.     }  
  83. }  
[java]  view plain  copy
 print ?
  1. package com.x.dao;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.data.redis.core.RedisTemplate;  
  5. import org.springframework.data.redis.serializer.RedisSerializer;  
  6.   
  7. /**  
  8.  * AbstractBaseRedisDao 
  9.  * @author http://blog.csdn.net/java2000_wl  
  10.  * @version <b>1.0</b>  
  11.  */   
  12. public abstract class AbstractBaseRedisDao<K, V> {  
  13.       
  14.     @Autowired  
  15.     protected RedisTemplate<K, V> redisTemplate;  
  16.   
  17.     /** 
  18.      * 设置redisTemplate 
  19.      * @param redisTemplate the redisTemplate to set 
  20.      */  
  21.     public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {  
  22.         this.redisTemplate = redisTemplate;  
  23.     }  
  24.       
  25.     /** 
  26.      * 获取 RedisSerializer 
  27.      * <br>------------------------------<br> 
  28.      */  
  29.     protected RedisSerializer<String> getRedisSerializer() {  
  30.         return redisTemplate.getStringSerializer();  
  31.     }  
  32. }  
[java]  view plain  copy
 print ?
  1. package com.x.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.x.entity.User;  
  6.   
  7. /**  
  8.  * @author http://blog.csdn.net/java2000_wl  
  9.  * @version <b>1.0</b>  
  10.  */   
  11. public interface IUserDao {  
  12.       
  13.     /** 
  14.      * 新增 
  15.      * <br>------------------------------<br> 
  16.      * @param user 
  17.      * @return 
  18.      */  
  19.     boolean add(User user);  
  20.       
  21.     /** 
  22.      * 批量新增 使用pipeline方式 
  23.      * <br>------------------------------<br> 
  24.      * @param list 
  25.      * @return 
  26.      */  
  27.     boolean add(List<User> list);  
  28.       
  29.     /** 
  30.      * 删除 
  31.      * <br>------------------------------<br> 
  32.      * @param key 
  33.      */  
  34.     void delete(String key);  
  35.       
  36.     /** 
  37.      * 删除多个 
  38.      * <br>------------------------------<br> 
  39.      * @param keys 
  40.      */  
  41.     void delete(List<String> keys);  
  42.       
  43.     /** 
  44.      * 修改 
  45.      * <br>------------------------------<br> 
  46.      * @param user 
  47.      * @return  
  48.      */  
  49.     boolean update(User user);  
  50.   
  51.     /** 
  52.      * 通过key获取 
  53.      * <br>------------------------------<br> 
  54.      * @param keyId 
  55.      * @return  
  56.      */  
  57.     User get(String keyId);  
  58. }  
[java]  view plain  copy
 print ?
  1. package com.x.dao.impl;  
  2.   
  3. import java.util.ArrayList;  
  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.RedisCallback;  
  9. import org.springframework.data.redis.serializer.RedisSerializer;  
  10. import org.springframework.util.Assert;  
  11.   
  12. import com.x.dao.AbstractBaseRedisDao;  
  13. import com.x.dao.IUserDao;  
  14. import com.x.entity.User;  
  15.   
  16. /**  
  17.  * Dao 
  18.  * @author http://blog.csdn.net/java2000_wl  
  19.  * @version <b>1.0</b>  
  20.  */   
  21. public class UserDao extends AbstractBaseRedisDao<String, User> implements IUserDao {  
  22.   
  23.     /**  
  24.      * 新增 
  25.      *<br>------------------------------<br> 
  26.      * @param user 
  27.      * @return 
  28.      */  
  29.     public boolean add(final User user) {  
  30.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  31.             public Boolean doInRedis(RedisConnection connection)  
  32.                     throws DataAccessException {  
  33.                 RedisSerializer<String> serializer = getRedisSerializer();  
  34.                 byte[] key  = serializer.serialize(user.getId());  
  35.                 byte[] name = serializer.serialize(user.getName());  
  36.                 return connection.setNX(key, name);  
  37.             }  
  38.         });  
  39.         return result;  
  40.     }  
  41.       
  42.     /** 
  43.      * 批量新增 使用pipeline方式   
  44.      *<br>------------------------------<br> 
  45.      *@param list 
  46.      *@return 
  47.      */  
  48.     public boolean add(final List<User> list) {  
  49.         Assert.notEmpty(list);  
  50.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  51.             public Boolean doInRedis(RedisConnection connection)  
  52.                     throws DataAccessException {  
  53.                 RedisSerializer<String> serializer = getRedisSerializer();  
  54.                 for (User user : list) {  
  55.                     byte[] key  = serializer.serialize(user.getId());  
  56.                     byte[] name = serializer.serialize(user.getName());  
  57.                     connection.setNX(key, name);  
  58.                 }  
  59.                 return true;  
  60.             }  
  61.         }, falsetrue);  
  62.         return result;  
  63.     }  
  64.       
  65.     /**  
  66.      * 删除 
  67.      * <br>------------------------------<br> 
  68.      * @param key 
  69.      */  
  70.     public void delete(String key) {  
  71.         List<String> list = new ArrayList<String>();  
  72.         list.add(key);  
  73.         delete(list);  
  74.     }  
  75.   
  76.     /** 
  77.      * 删除多个 
  78.      * <br>------------------------------<br> 
  79.      * @param keys 
  80.      */  
  81.     public void delete(List<String> keys) {  
  82.         redisTemplate.delete(keys);  
  83.     }  
  84.   
  85.     /** 
  86.      * 修改  
  87.      * <br>------------------------------<br> 
  88.      * @param user 
  89.      * @return  
  90.      */  
  91.     public boolean update(final User user) {  
  92.         String key = user.getId();  
  93.         if (get(key) == null) {  
  94.             throw new NullPointerException("数据行不存在, key = " + key);  
  95.         }  
  96.         boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {  
  97.             public Boolean doInRedis(RedisConnection connection)  
  98.                     throws DataAccessException {  
  99.                 RedisSerializer<String> serializer = getRedisSerializer();  
  100.                 byte[] key  = serializer.serialize(user.getId());  
  101.                 byte[] name = serializer.serialize(user.getName());  
  102.                 connection.set(key, name);  
  103.                 return true;  
  104.             }  
  105.         });  
  106.         return result;  
  107.     }  
  108.   
  109.     /**  
  110.      * 通过key获取 
  111.      * <br>------------------------------<br> 
  112.      * @param keyId 
  113.      * @return 
  114.      */  
  115.     public User get(final String keyId) {  
  116.         User result = redisTemplate.execute(new RedisCallback<User>() {  
  117.             public User doInRedis(RedisConnection connection)  
  118.                     throws DataAccessException {  
  119.                 RedisSerializer<String> serializer = getRedisSerializer();  
  120.                 byte[] key = serializer.serialize(keyId);  
  121.                 byte[] value = connection.get(key);  
  122.                 if (value == null) {  
  123.                     return null;  
  124.                 }  
  125.                 String name = serializer.deserialize(value);  
  126.                 return new User(keyId, name, null);  
  127.             }  
  128.         });  
  129.         return result;  
  130.     }  
  131. }  
[java]  view plain  copy
 print ?
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. import junit.framework.Assert;  
  5.   
  6. import org.junit.Test;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.test.context.ContextConfiguration;  
  9. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
  10.   
  11. import com.x.dao.IUserDao;  
  12. import com.x.entity.User;  
  13.   
  14. /**  
  15.  * 测试 
  16.  * @author http://blog.csdn.net/java2000_wl  
  17.  * @version <b>1.0</b>  
  18.  */    
  19. @ContextConfiguration(locations = {"classpath*:applicationContext.xml"})  
  20. public class RedisTest extends AbstractJUnit4SpringContextTests {  
  21.       
  22.     @Autowired  
  23.     private IUserDao userDao;  
  24.       
  25.     /** 
  26.      * 新增 
  27.      * <br>------------------------------<br> 
  28.      */  
  29.     @Test  
  30.     public void testAddUser() {  
  31.         User user = new User();  
  32.         user.setId("user1");  
  33.         user.setName("java2000_wl");  
  34.         boolean result = userDao.add(user);  
  35.         Assert.assertTrue(result);  
  36.     }  
  37.       
  38.     /** 
  39.      * 批量新增 普通方式 
  40.      * <br>------------------------------<br> 
  41.      */  
  42.     @Test  
  43.     public void testAddUsers1() {  
  44.         List<User> list = new ArrayList<User>();  
  45.         for (int i = 10; i < 50000; i++) {  
  46.             User user = new User();  
  47.             user.setId("user" + i);  
  48.             user.setName("java2000_wl" + i);  
  49.             list.add(user);  
  50.         }  
  51.         long begin = System.currentTimeMillis();  
  52.         for (User user : list) {  
  53.             userDao.add(user);  
  54.         }  
  55.         System.out.println(System.currentTimeMillis() -  begin);  
  56.     }  
  57.       
  58.     /** 
  59.      * 批量新增 pipeline方式 
  60.      * <br>------------------------------<br> 
  61.      */  
  62.     @Test  
  63.     public void testAddUsers2() {  
  64.         List<User> list = new ArrayList<User>();  
  65.         for (int i = 10; i < 1500000; i++) {  
  66.             User user = new User();  
  67.             user.setId("user" + i);  
  68.             user.setName("java2000_wl" + i);  
  69.             list.add(user);  
  70.         }  
  71.         long begin = System.currentTimeMillis();  
  72.         boolean result = userDao.add(list);  
  73.         System.out.println(System.currentTimeMillis() - begin);  
  74.         Assert.assertTrue(result);  
  75.     }  
  76.       
  77.     /** 
  78.      * 修改 
  79.      * <br>------------------------------<br> 
  80.      */  
  81.     @Test  
  82.     public void testUpdate() {  
  83.         User user = new User();  
  84.         user.setId("user1");  
  85.         user.setName("new_password");  
  86.         boolean result = userDao.update(user);  
  87.         Assert.assertTrue(result);  
  88.     }  
  89.       
  90.     /** 
  91.      * 通过key删除单个 
  92.      * <br>------------------------------<br> 
  93.      */  
  94.     @Test  
  95.     public void testDelete() {  
  96.         String key = "user1";  
  97.         userDao.delete(key);  
  98.     }  
  99.       
  100.     /** 
  101.      * 批量删除 
  102.      * <br>------------------------------<br> 
  103.      */  
  104.     @Test  
  105.     public void testDeletes() {  
  106.         List<String> list = new ArrayList<String>();  
  107.         for (int i = 0; i < 10; i++) {  
  108.             list.add("user" + i);  
  109.         }  
  110.         userDao.delete(list);  
  111.     }  
  112.       
  113.     /** 
  114.      * 获取 
  115.      * <br>------------------------------<br> 
  116.      */  
  117.     @Test  
  118.     public void testGetUser() {  
  119.         String id = "user1";  
  120.         User user = userDao.get(id);  
  121.         Assert.assertNotNull(user);  
  122.         Assert.assertEquals(user.getName(), "java2000_wl");  
  123.     }  
  124.   
  125.     /** 
  126.      * 设置userDao 
  127.      * @param userDao the userDao to set 
  128.      */  
  129.     public void setUserDao(IUserDao userDao) {  
  130.         this.userDao = userDao;  
  131.     }  
  132. }  
目录
相关文章
|
18天前
|
NoSQL Java 调度
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
分布式锁是分布式系统中用于同步多节点访问共享资源的机制,防止并发操作带来的冲突。本文介绍了基于Spring Boot和Redis实现分布式锁的技术方案,涵盖锁的获取与释放、Redis配置、服务调度及多实例运行等内容,通过Docker Compose搭建环境,验证了锁的有效性与互斥特性。
分布式锁与分布式锁使用 Redis 和 Spring Boot 进行调度锁(不带 ShedLock)
|
5月前
|
NoSQL 安全 Java
深入理解 RedisConnectionFactory:Spring Data Redis 的核心组件
在 Spring Data Redis 中,`RedisConnectionFactory` 是核心组件,负责创建和管理与 Redis 的连接。它支持单机、集群及哨兵等多种模式,为上层组件(如 `RedisTemplate`)提供连接抽象。Spring 提供了 Lettuce 和 Jedis 两种主要实现,其中 Lettuce 因其线程安全和高性能特性被广泛推荐。通过手动配置或 Spring Boot 自动化配置,开发者可轻松集成 Redis,提升应用性能与扩展性。本文深入解析其作用、实现方式及常见问题解决方法,助你高效使用 Redis。
570 4
|
6月前
|
NoSQL Java 关系型数据库
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
272 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
|
2月前
|
NoSQL Java Redis
Redis基本数据类型及Spring Data Redis应用
Redis 是开源高性能键值对数据库,支持 String、Hash、List、Set、Sorted Set 等数据结构,适用于缓存、消息队列、排行榜等场景。具备高性能、原子操作及丰富功能,是分布式系统核心组件。
381 2
|
4月前
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
186 32
|
6月前
|
NoSQL Java API
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
1657 0
|
6月前
|
NoSQL Java Redis
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
151 0
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
756 0
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
558 0
|
NoSQL Java Redis
Springboot最全权限集成Redis-前后端分离-springsecurity-jwt-Token4
Springboot最全权限集成Redis-前后端分离-springsecurity-jwt-Token4
209 71