在上期的 SSM 初始框架下开发SSM 初始项目实例
一、maven 引入 spring 相关包
1、 Jedis
编辑 pom.xml
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0-rc</version>
</dependency>
2、 Spring Data Redis
编辑 pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
二、配置 redisTemplate
1、如下目录新增配置文件

配置文件内容如下
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置JedisPoolConfig相关参数 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="100"/>
<property name="maxIdle" value="20"/>
<property name="minIdle" value="3"/>
<property name="maxWaitMillis" value="2000"/>
</bean>
<!-- 配置redis服务器信息 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="192.168.109.128" p:port="6379"
p:poolConfig-ref="poolConfig" p:password="redis"/>
<bean id="genericJackson2JsonRedisSerializer" class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
<bean id= "stringRedisSerializer" class= "org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean id= "redisTemplate" class= "org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="keySerializer" ref="stringRedisSerializer"/>
<property name="valueSerializer" ref="genericJackson2JsonRedisSerializer" />
</bean>
</beans>
注意jedisConnectionFactory
内的p
标签需要引入xmlns:p="http://www.springframework.org/schema/p"
才能识别
2、配置要点
key 序列化
采用StringRedisSerializer
value 序列化
采用GenericJackson2JsonRedisSerializer
3、配置 web.xml
修改context-param
部分,自动加载所有spring
配置
<!--加载Spring IOC容器-->
<context-param>
<!--配置SpringIOC容器所在的地址,如果不配,则默认应该放在WEB-INF目录下,且该文件必须已 【-servlet.xml】结尾-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</context-param>
三、自动注入使用
1、修改RoleService
类
添加如下测试代码
@Autowired
private RedisTemplate redisTemplate;
private Role testJedisTemplate(Role role){
redisTemplate.opsForValue().set(role.getId(), role);
return (Role)redisTemplate.opsForValue().get(role.getId());
}
2、启动报错
Caused by: java.lang.IllegalStateException: Failed to introspect Class [org.springframework.data.redis.connection.jedis.JedisConnectionFactory] from ClassLoader [ParallelWebappClassLoader
context: ROOT
delegate: false
原因:redis jar版本与spring不匹配
去 Spring Data Redis查看当前使用的2.1.9
版本

所以需要将 jedis 的版本更改为
2.9.3
四、运行
可以看到 redis 中的信息如图

网友评论