一、Spring整合Redis
1.1 在SSM项目中配置Redis
第一步:下载jar包(https://mvnrepository.com/);
jedis-2.9.1
spring-data-commons-1.8.4.RELEASE
spring-data-redis-1.6.2.RELEASE
注意:由于不同版本可能会导致整合失败,所以建议下载上面版本的jar包。
第二步:导入jar到工程中;
第三步:在src目录下新建redis.properties配置文件;
# redis服务器的地址
redis.host=127.0.0.1
# redis服务器的端口
redis.port=6379
# 登录密码
redis.pwd=
# redis提供了16个数据库,每个数据库都是以数字进行编号,第一个数据库的编号为0。如果没有指定使用哪个数据库,默认使用的是第0个数据库
redis.database=0
# 超时时间,以毫秒为单位
redis.timeout=1000
# 是否使用连接池
redis.userPool=true
# 最大空闲的连接数
redis.pool.maxIdle=100
# 最小空闲的连接数
redis.pool.minIdle=10
# 最大活动对象数
redis.pool.maxTotal=200
# 连接池没有空闲对象时候的等待时间
redis.pool.maxWaitMillis=10000
# 表示一个对象停留在idle状态的最短时间,只有在timeBetweenEvictionRunsMillis大于0的时候才有意义
redis.pool.minEvictableIdleTimeMillis=300000
# “空闲链接”检测线程每次扫描的对象数
redis.pool.numTestsPerEvictionRun=10
# “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1.
redis.pool.timeBetweenEvictionRunsMillis=30000
# 在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的
redis.pool.testOnBorrow=true
# 当对象返回给连接池的时候,是否提前进行validate操作
redis.pool.testOnReturn=true
# 如果为true,表示有一个 “空闲链接”检测线程对空闲对象进行扫描,如果validate失败,此对象会被从连接池中删除掉。
# 这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
redis.pool.testWhileIdle=true
第四步:创建spring-redis配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:redis="http://www.springframework.org/schema/redis" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/redis
http://www.springframework.org/schema/redis/spring-redis.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
">
<!-- 指定配置文件位置 -->
<context:property-placeholder order="1" location="classpath:redis.properties" ignore-unresolvable="true"/>
<!-- 指定连接池的配置参数 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="minIdle" value="${redis.pool.minIdle}" />
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
<property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"></property>
<property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"></property>
<property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"></property>
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
<property name="testOnReturn" value="${redis.pool.testOnReturn}" />
<property name="testWhileIdle" value="${redis.pool.testWhileIdle}"></property>
</bean>
<!-- 配置连接池 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="jedisPoolConfig" />
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<property name="password" value="${redis.pwd}" />
<property name="usePool" value="${redis.userPool} " />
<property name="database" value="${redis.database}" />
<property name="timeout" value="${redis.timeout}" />
</bean>
<!-- 配置RedisTemplate对象 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<!-- 序列化方式 建议key/hashKey采用StringRedisSerializer -->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="enableTransactionSupport" value="false" />
</bean>
<!-- 对string操作的封装 -->
<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<constructor-arg ref="jedisConnectionFactory" />
<!-- 开启REIDS事务支持 -->
<property name="enableTransactionSupport" value="false" />
</bean>
</beans>
第五步:在applicationContext.xml文件中引用spring-redis.xml文件。
<import resource="classpath:spring-redis.xml" />
1.2 在SSM项目中使用Redis
第一步:创建Redis的业务组件。
public interface IRedisService {
/**
* 存储key-value
* @param key
* @param value
*/
void setData(String key, String value);
/**
* 根据key查询
* @param key 健
* @return
*/
Object getData(String key);
}
@Service
public class RedisServiceImpl implements IRedisService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public void setData(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
@Override
public Object getData(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
}
第二步:把业务组件注入控制器,然后调用业务组件的方法操作redis数据库。
@Controller
public class NewsController {
@Autowired
private IRedisService redisService;
@RequestMapping("/news/list")
public void list() {
System.out.println("执行list...");
//redisService.setData("aa", "999");
Object res = redisService.getData("aa");
System.out.println("res = " + res);
}
}
二、SpringBoot整合Redis
第一步:配置pom。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
第二步:配置redis。
spring:
redis:
database: 0
host: 192.168.3.19
port: 6379
password:
pool:
max-active: 200
max-wait: -1
max-idle: 10
min-idle: 0
timeout: 1000
属性文件配置:
spring.redis.database=1
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.pwd=
spring.redis.pool.maxActive=200
spring.redis.pool.maxWait=1
spring.redis.pool.maxIdle=10
spring.redis.pool.minIdle=0
spring.redis.timeout=1000
第三步:在控制器类中注入RedisTemplate对象,然后在方法中通过该对象提供方法操作Redis;
@RestController
public class TestController {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@RequestMapping("/setValue")
public void setValue(String key, String value) throws UnsupportedEncodingException {
redisTemplate.boundValueOps(key).set(value);
}
@RequestMapping("/getValue")
public Object getValue(String key) throws UnsupportedEncodingException {
Object value = redisTemplate.boundValueOps(key).get();
return value;
}
@RequestMapping("/exist")
public String exist(String key) throws UnsupportedEncodingException {
key = URLDecoder.decode(key, "utf-8");
boolean flag = redisTemplate.hasKey(key);
return flag ? "ok" : "key not found";
}
}
第四步:创建启动类。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}