Redis整合Spring

redis整合进spring项目,需要在项目中添加以下jar包

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.5.1</version>
        </dependency>

        <dependency>
           <groupId>
           org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.3.0.RELEASE</version>
        </dependency>

项目中的redis作为客户端,需要一个配置文件对访问redis服务端进行配置,和数据库数据源配置类似,可以使用properties文件填写配置项:

#=============Redis===============
redis.host = 127.0.0.1
redis.port = 6379
redis.maxTotal = 300
redis.maxIdle = 100
redis.maxWaitMillis = 1000
redis.testOnBorrow = true
redis.pass =
redis.timeout = 100000
redis.default.db = 0

这些配置项和连接池的配置类似,不再赘述。既然要将redis与spring相整合,就需要在spring配置文件中配置需要托管的类:

<!-- jedis pool配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxTotal}" />
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <!-- spring data redis -->
    <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="password" value="${redis.pass}" />
         -->
        <property name="timeout" value="${redis.timeout}" />
        <property name="database" value="${redis.default.db}"></property>
        <constructor-arg index="0" ref="jedisPoolConfig" />
    </bean>

    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
    </bean>

项目中使用了字符串做缓存所以配置了stringRedisTemplate,通过spring注入 stringRedisTemplate:

@Resource
    protected StringRedisTemplate stringRedisTemplate;

写入:

stringRedisTemplate.opsForValue().set(key, JsonString);

读出:

stringRedisTemplate.opsForValue().get(key);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值