Spirng+redis+redisTemplate

前提

在使用项目使用redis的时候,刚开始用的是redisPool来管理redis,但是用了一段时间发现redis的connect_clients高居不下,经常容易因为连接数太高而报错。

原因

随即去网上百度了,原来是redispool每次来一个请求都会创立一个连接,而且不知道是不是因为我配置有问题,释放时间没有用。最后发现redisTemplate能帮我们管理redis连接,开发者只要拿来存取就好。

开始

1.maven引入redis相关包

  <!-- redis缓存 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.6.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <!-- spring-redis -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.4.2.RELEASE</version>
        </dependency>

2.resource下新建redis/reids.properties配置文件。内容如下:

#redis地址
redis.host=127.0.0.1
#端口号
redis.port=6379
#最大连接数
redis.maxTotal=100
#最大空闲连接数
redis.maxIdle=30
#每次释放连接的最大数目
redis.numTestsPerEvictionRun=1024
#释放连接的扫描间隔(毫秒)
redis.timeBetweenEvictionRunsMillis=3000
#连接最小空闲时间
redis.minEvictableIdleTimeMillis=4000
#连接空闲多久后释放,当空闲时间>该值,且 空闲连接>最大空闲连接数 时直接释放
redis.softMinEvictableIdleTimeMillis=10000
#获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1
redis.maxWaitMillis=1500
#在获取连接的时候检查有效性,默认false
redis.testOnBorrow=true

3.applicationContext.xml文件配置redis。内容如下:

<!--redis的配置-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!--最大空闲连接数-->
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <!--每次释放连接的最大数目-->
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
        <!--释放连接的扫描间隔(毫秒)-->
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
        <!--连接最小空闲时间-->
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
        <!--连接空闲多久后释放,当空闲时间>该值,且 空闲连接>最大空闲连接数 时直接释放-->
        <property name="softMinEvictableIdleTimeMillis" value="${redis.softMinEvictableIdleTimeMillis}"/>
        <!--获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1-->
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
        <!--在获取连接的时候检查有效性,默认false-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        <!--最大连接数-->
        <property name="maxTotal" value="${redis.maxTotal}"/>
    </bean>
    <!-- redis连接工厂 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"></property>
        <property name="port" value="${redis.port}"></property>
        <property name="password" value=""></property>
        <property name="poolConfig" ref="jedisPoolConfig"></property>
    </bean>

    <!-- redis操作模板,这里采用尽量面向对象的模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--  	如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
    </bean>

注意!此处要注意引入redis.properties文件,因为有多个properties文件,添加如下:

<context:property-placeholder location="classpath:/*/*.properties"/>

4.到这里,已经完成把redis整合到了spring里,接下来可以新增一个reids工具类redisUtil.内容如下:

package com.bbkj.common.redis;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * @author JJ
 * @version 1.0
 * @description: TODO
 * @date 2022/1/5 16:17
 */
@Component("redisUtil")
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void put(String key, String value) {
        if (key == null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForHash().put(key, key, value);
    }


    public void set(String key, String value) {
        if (key == null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, String value, long timeout) {
        if (key == null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    public void set(String key, String value, long timeout, String TimeType) {

        if (key == null || "".equals(key)) {
            return;
        }
        if (TimeType == "s") {
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
        }
        if (TimeType == "h") {
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.HOURS);
        }
        if (TimeType == "d") {
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.DAYS);
        }

    }


    public String get(String key) {
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            return null;
        } else {
            return String.valueOf(obj);
        }
    }

}

5.使用,如下:

获取redisutil:

@Autowired
    private RedisUtil redisUtil;

往redis写入内容

redisUtil.set(String.valueOf(person_id), jsonObject.toString());

获取redis的内容

String info = String.valueOf(redisUtil.get(personId));

往redis写入有时效的内容

redisUtil.set("indexData", result.toString(), 1, "d");

先写到,有其他内容再补充,学无止境呀!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值