Spring+Dubbo集成Redis的两种解决方案
当下我们的系统数据库压力都非常大,解决数据库的瓶颈问题势在必行,为了解决数据库的压力等需求,我们常用的是各种缓存,比如redis,本文就来简单讲解一下如何集成redis缓存存储,附github源码。
环境准备
· redis
· IDEA 开发工具
· JDK 1.8及以上
· Maven 4.0及以上
redis的搭建网上有很多例子,这里就不细讲了,友友们可以网上浏览安装一波,下面我们就直接讲如何在spring中集成redis。
资源配置
1、spring集成redis
第一步我们先设置maven的pom.xml引用,代码如下:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
设置完引用以后,就可以开始着手编写redis在spring中的配置文件了,下面直接上代码 applicationContext.xml
文件:
<!-- redis -->
<import resource="spring-redis.xml" />
spring-redis.xml
文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 加载redis参数 -->
<context:property-placeholder location="classpath:redis.properties" />
<!-- 自动注解 -->
<!--<context:component-scan base-package="service.impl" />-->
<!-- jedis 连接池配置参数: -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 设置最大连接数 -->
<property name="maxTotal" value="${redis.maxActive}"></property>
<!-- 设置最大空闲数 -->
<property name="maxIdle" value="${redis.maxIdle}"></property>
<!-- 设置超时时间 -->
<property name="maxWaitMillis" value="${redis.maxWait}"></property>
<property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
<property name="testOnReturn" value="${redis.testOnReturn}"></property>
</bean>
<!-- jedis 连接池 连接本地redis服务 构造器注入 -->
<bean id="pool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="poolConfig"/>
<constructor-arg index="1" value="${redis.host}"/>
<constructor-arg index="2" value="${redis.port}"/>
<constructor-arg index="3" value="${redis.maxWait}"/>
<constructor-arg index="4" value="${redis.pass}"/>
</bean>
<!-- redis cache config -->
<bean id="redisCache" class="client.RedisCache">
<property name="pool" ref="pool"/>
</bean<