SSH项目集成redis(缓存示例)

本文详细介绍如何在Spring项目中集成Redis,包括添加依赖、配置文件、编写Redis类等步骤,并给出缓存使用的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文默认你已经部署了redis并成功启动,否则将无法成功运行代码。

1、添加jar包

redis所需jar包:

  • commons-pool2-x.x.x.jar
  • jedis-x.x.x.jar
  • spring-data-redis-x.x.x.RELEASE.jar

楼主用的版本号为:

  • commons-pool2-1.5.4.jar
  • jedis-2.3.1.jar
  • spring-data-redis-1.3.4.RELEASE.jar

Eclipse中导入外部jar包步骤参考百度经验《Eclipse中导入外部jar包

2、Redis配置文件

在resources文件夹下面新建一个redis.properties文件,内容如下:

# redis服务器地址
redis.host=127.0.0.1
# redis监听端口,默认端口为6379
redis.port=6379
# redis密码
redis.password=
# 指定redis 数据库,默认值 0
redis.default.db=1
# 当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能
redis.timeout=1000
# 连接池的最大数据库连接数,设为0表示无限制
redis.maxActive=200
# 最大空闲连接数
redis.maxIdle=10
# 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1
redis.maxWait=-1
# 在获取连接的时候检查有效性, 默认false
redis.testOnBorrow=true

再新建一个redis.xml,内容如下:

<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"
       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-4.0.xsd">
    <context:property-placeholder location="classpath:redis.properties"/>
    <bean id="propertyConfigurerRedis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="1"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="systemPropertiesMode" value="1"/>
        <property name="searchSystemEnvironment" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="usePool" value="true"></property>
        <property name="hostName" value="${redis.host}"/>
        <property name="port" value="${redis.port}"/>
        <property name="timeout" value="${redis.timeout}"/>
        <property name="database" value="${redis.default.db}"/>
        <constructor-arg index="0" ref="jedisPoolConfig"/>
    </bean>
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"
          p:connectionFactory-ref="jedisConnectionFactory"/>
    <bean id="redisBase" abstract="true">
        <property name="template" ref="redisTemplate"/>
    </bean>
    <context:component-scan base-package="com.jerry.redis"/>
</beans>

3、Redis类

新建一个com.jerry.redis包,下面的类都建在此包下。

3.1、接口IRedisService

public interface IRedisService<K, V> {
	public void set(K key, V value, long expiredTime);

	public V get(K key);

	public Object getHash(K key, String name);

	public void del(K key);
}

3.2、抽象类AbstractRedisService,主要是对RedisTemplate进行操作:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

public abstract class AbstractRedisService<K, V> implements IRedisService<K, V> {
	@Autowired
	private RedisTemplate<K, V> redisTemplate;

	public RedisTemplate<K, V> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void set(final K key, final V value, final long expiredTime) {
		BoundValueOperations<K, V> valueOper = redisTemplate.boundValueOps(key);
		if (expiredTime <= 0) {
			valueOper.set(value);
		} else {
			valueOper.set(value, expiredTime, TimeUnit.MILLISECONDS);
		}
	}

	@Override
	public V get(final K key) {
		BoundValueOperations<K, V> valueOper = redisTemplate.boundValueOps(key);
		return valueOper.get();
	}

	@Override
	public Object getHash(K key, String name) {
		Object res = redisTemplate.boundHashOps(key).get(name);
		return res;
	}

	@Override
	public void del(K key) {
		if (redisTemplate.hasKey(key)) {
			redisTemplate.delete(key);
		}
	}

}

3.3、实现类RedisService

import org.springframework.stereotype.Service;

@Service("redisService")
public class RedisService extends AbstractRedisService<String, Object> { 
	  
}

3.4、工具类RedisTool

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RedisTool {
	private static ApplicationContext factory;
	
	private static RedisService redisService;

	public static ApplicationContext getFactory() {
		if (factory == null) {
			factory = new ClassPathXmlApplicationContext("classpath:redis.xml");
		}
		return factory;
	}

	public static RedisService getRedisService() {
		if (redisService == null) {
			redisService = (RedisService) getFactory().getBean("redisService");
		}
		return redisService;
	}

}

4、Redis缓存使用示例

	
	/**
	 * redis对象
	 */
	public RedisService redisService = RedisTool.getRedisService();
	
	/**
	 * 缓存时间(单位:ms)
	 */
	public long redisExpiredTime = 1000 * 60 * 60 * 24L;
	
	protected String getData() {
		// redis缓存的key
		String redisKey = "data" ;
		// 去缓存中获取key对应的值
		String str = (String) redisService.get(redisKey);
		// 如果缓存中不存在值,执行查询逻辑,否则之间返回
		if(null == str || str.isEmpty()){
				// TODO 业务查询逻辑
				str = sb.toString();//查询逻辑得到的值
				// 将值存入缓存
				redisService.set(redisKey, str, redisExpiredTime);
			}
		}
		return str;
	}

相关文章
1、springboot 使用 RedisTemplate 整合 Redis 实现并发锁以及redis工具类
2、springboot 使用 Jedis、RedisTemplate 整合 Redis 实现并发锁

本文参考文章:https://www.jb51.net/article/109515.htm

PS:
如果博文有写的不对或者有更好的方式,欢迎大家评论或者私信指正。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值