您好,登錄后才能下訂單哦!
本篇文章為大家展示了Redis如何在Spring中使用,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
Eclipse工程結(jié)構(gòu)
如下圖為我的示例工程的結(jié)構(gòu)圖,采用Maven構(gòu)建。其中需要集成Spring,因此需要beans.xml文件配置spring的依賴注入,redis.properties配置連接服務器的配置信息。
其中工程中beans.xml和redis.properties文件直接放在了根目錄,有需要的讀者可以放到resource目錄中。
POM依賴
如下為示例POM依賴,Spring集成redis需要依賴的包為:jedis包,spring-context模塊及依賴的包,spring-data-redis模塊包,spring-test包用于JUnit測試,pom.xml文件內(nèi)容如下:
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.test</groupid> JavaTest</artifactid> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>JavaTest</name> <url>https://maven.apache.org</url> <properties> <project.build.sourceencoding>UTF-8</project.build.sourceencoding> </properties> <dependencies> <dependency> <groupid>junit</groupid> junit</artifactid> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupid>redis.clients</groupid> jedis</artifactid> <version>2.5.1</version> </dependency> <dependency> <groupid>org.springframework</groupid> spring-context</artifactid> <version>4.2.6.RELEASE</version> <scope>runtime</scope> </dependency> <dependency> <groupid>org.springframework</groupid> spring-test</artifactid> <version>4.2.6.RELEASE</version> <scope>runtime</scope> </dependency> <dependency> <groupid>org.springframework.data</groupid> spring-data-redis</artifactid> <version>1.7.2.RELEASE</version> </dependency> </dependencies> </project>
Spring配置
Spring配置文件beans.xml的配置如下:
<!--?xml version="1.0" encoding="UTF-8"?--> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:aop="https://www.springframework.org/schema/aop" xmlns:context="https://www.springframework.org/schema/context" xmlns:jee="https://www.springframework.org/schema/jee" xmlns:p="https://www.springframework.org/schema/p" xmlns:tx="https://www.springframework.org/schema/tx" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation=" https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加載classpath下的Redis配置文件 --> <context:property-placeholder location="classpath:redis.properties"> <bean class="redis.clients.jedis.JedisPoolConfig" id="poolConfig"> <property name="maxIdle" value="${redis.maxIdle}"> <property name="testOnBorrow" value="${redis.testOnBorrow}"> </property></property></bean> <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" id="connectionFactory" p:host-name="${redis.host}" p:password="${redis.pass}" p:pool-config-ref="poolConfig" p:port="${redis.port}"> <!-- spring提供的模板類 --> <bean class="org.springframework.data.redis.core.StringRedisTemplate" id="redisTemplate"> <property name="connectionFactory" ref="connectionFactory"> </property></bean> <bean class="com.redis.test.UserDao" id="userDao"> <property name="redisTemplate" ref="redisTemplate"> </property></bean> </bean></context:property-placeholder></beans>
在beans.xml配置文件中,需要先加載redis.properties文件。
Redis配置信息
Redis的配置信息在redis.properties文件中配置:
# Redis地址和端口和連接密碼 redis.host=localhost redis.port=6379 redis.pass= redis.maxIdle=300 redis.testOnBorrow=true
此示例,連接Redis服務器時沒有設置連接密碼,因此不用填值。
Java代碼
User.java
package com.redis.test; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 3409768855488864675L; private String id; private String name; private String password; public User() { } public User(String id, String name, String password) { this.id = id; this.name = name; this.password = password; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + "]"; } }
AbstractRedisBaseDao.java
package com.redis.test; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; public abstract class AbstractRedisBaseDao<k, v=""> { protected RedisTemplate<k, v=""> redisTemplate; public RedisTemplate<k, v=""> getRedisTemplate() { return redisTemplate; } public void setRedisTemplate(RedisTemplate<k, v=""> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 獲取 RedisSerializer */ protected RedisSerializer<string> getRedisSerializer() { return redisTemplate.getStringSerializer(); } }
IUserDao.java
package com.redis.test; import java.util.List; public interface IUserDao { /** 新增 */ Boolean add(User user); /** 批量新增,pipeline方式 */ Boolean add(List<user> list); /** 刪除 */ void delete(String key); /** 批量刪除 */ void delete(List<string> keys); /** 更新 */ Boolean update(User user); /** 讀取 */ User get(String keyId); }
UserDao.java
package com.redis.test; 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; public class UserDao extends AbstractRedisBaseDao<string, user=""> implements IUserDao { 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()); // 將ID序列化成key byte[] value = serializer.serialize(user.getName()); return connection.setNX(key, value); } } ); return result; } 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 (int i = 0; i < list.size(); i++) { User user = list.get(i); byte[] key = serializer.serialize(user.getId()); // 將ID序列化成key byte[] value = serializer.serialize(user.getName()); connection.setNX(key, value); } return true; } } , false, true); return result; } public void delete(String key) { redisTemplate.delete(key); } public void delete(List<string> keys) { redisTemplate.delete(keys); } public Boolean update(final User user) { String key = user.getId(); if(get(key) == null) { throw new NullPointerException("數(shù)據(jù)行不存在,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()); // 將ID序列化成key byte[] value = serializer.serialize(user.getName()); connection.set(key, value); return true; } } ); return result; } public User get(final String keyId) { User user = 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 user; } }
RedisTest.java(JUnit測試類)
package com.redis.test; import java.util.ArrayList; import java.util.List; 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 org.springframework.util.Assert; /** * junit在Spring context環(huán)境下測試 */ @ContextConfiguration(locations={"classpath*:beans.xml"}) public class RedisTest extends AbstractJUnit4SpringContextTests { @Autowired private IUserDao userDao; /** 增加單個用戶 */ @Test public void testAddUser() { User user = new User("user1", "password1", null); Boolean result = userDao.add(user); Assert.isTrue(result); System.out.println("添加結(jié)果:" + result); } /** 批量新增普通方式,5286ms */ @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("password" + i); list.add(user); } long begin = System.currentTimeMillis(); for (User user : list) { userDao.add(user); } System.out.println(System.currentTimeMillis() - begin); } /** 批量新增pipeline方式,484ms */ @Test public void testAddUsers2() { List<user> list = new ArrayList<user>(); for (int i = 50000; i < 100000; i++) { User user = new User(); user.setId("user" + i); user.setName("password" + i); list.add(user); } long begin = System.currentTimeMillis(); Boolean result = userDao.add(list); Assert.isTrue(result); System.out.println(System.currentTimeMillis() - begin); } /** 更新 */ @Test public void testUpdate() { User user = new User(); user.setId("user1"); user.setName("new_password"); Boolean result = userDao.update(user); Assert.isTrue(result); } /** 刪除 */ @Test public void testDelete() { String key = "user1"; userDao.delete(key); } /** 批量刪除 */ @Test public void testDeletes() { List<string> list = new ArrayList<string>(); for (int i = 0; i < 10; i++) { list.add("user" + i); } userDao.delete(list); } /** 讀取 */ @Test public void testGetUser() { String id = "user1"; User user = userDao.get(id); Assert.notNull(user); System.out.println(user); } }
上述內(nèi)容就是Redis如何在Spring中使用,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。