Spring集成Redis详解代码示例
作者:yangkang029 发布时间:2023-05-04 00:58:25
标签:redis,spring,集成
本文章从头开始介绍Spring集成Redis的示例。
Eclipse工程结构
如下图为我的示例工程的结构图,采用Maven构建。其中需要集成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文件内容如下:
<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("数据行不存在,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环境下测试
*/
@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("添加结果:" + 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);
}
}
总结
浅谈spring 常用注解
spring中的FactoryBean代码示例
浅谈Spring的两种配置容器
如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
来源:https://www.2cto.com/kf/201609/543944.html


猜你喜欢
- 在一次Java解析xml文件的开发过程中,使用SAX解析时,出现了这样一个异常信息:Error on line 60 of document
- 目标:了解Swagger的作用和概念了解前后端分离在springBoot中集成SwaggerSwagger简介前后端分离VUE+spring
- Jmeter 执行Java 请求时,运行结束后报错,Tidying up remote @ Mon Feb 24 19:42:34 CST
- 在上篇文章给大家介绍了Spring boot + mybatis + Vue.js + ElementUI 实现数据的增删改查实例代码(一)
- 方法有4种:使用 String 类的 valueOf() 方法使用字符串连接使用 Character 类的 toString() 方法使用字
- Android中获取资源 id 及资源 id 的动态获取我们平时获取资源是通过 findViewById 方法进行的,比如我们常
- 本篇主要讲解SpringBoot当中使用Servlet三大组件,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学
- 前言前几篇文章着重介绍了后端服务数据库和多线程并行处理优化,并示例了改造前后的伪代码逻辑。当然了,优化是无止境的,前人栽树后人乘凉。作为我们
- 为什么需要协程?协程可以简化异步编程,可以顺序地表达程序,协程也提供了一种避免阻塞线程并用更廉价、更可控的操作替代线程阻塞的方法 &
- // Create a handler for a click event.button1.Click += delegate(System
- 前言:小编引入的图片和文字描述都是来自于尚硅谷的视频讲解,在此感谢尚硅谷的老师,同时也结合 seata文档官方文档进行整合项目地址(gite
- 本文实例为大家分享了Android实现密码明密文切换的具体代码,供大家参考,具体内容如下小眼睛在密码栏右边!奉上我使用的素材:添加图片到re
- 做了2,3年的java-web,始终木有逃离所谓基础业务,增删改查这些一成不变的东西写起来浪费大量时间,于是做了个简单的代码生成器快速生成代
- Java8 移除两个相同List对象List<Data> data1 = new ArrayList<>(
- 1 前言敏感词过滤就是你在项目中输入某些字(比如输入xxoo相关的文字时)时要能检测出来,很多项目中都会有一个敏感词管理模块,在敏感词管理模
- 导出excel是咱Java开发的必备技能啦,之前项目有这个功能,现在将其独立出来,分享一下。所用技术就是SpringBoot,然后是MVC架
- 最近总是有人来和我说我以前写的一个小app无法正常获取数据~Android简易版天气预报app 今天就又运行了下来查找问题,发现或许是接口有
- 话不多说,请看代码:package com.lxj.demo;import java.io.BufferedReader;import ja
- 前提最近发现各个频道推荐了很多ULID相关文章,这里对ULID的规范文件进行解读,并且基于Java语言自行实现ULID,通过此实现过程展示U
- 介绍大家都知道微信支付的回调链接要求不能跟参数,但又要接收返回的xml数据。我开始使用@RequestBody注解在参数上,希望能获取xml