首页导入相关依赖
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
在spring.xml配置文件添加bean节点
<!-- 配置jedis连接池的配置的初始化属性 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 配置最大连接数 -->
<property name="maxTotal" value="10"></property>
<!-- 配置初始连接数量 -->
<property name="maxIdle" value="2"></property>
</bean>
<!-- 配置Jedis(Redis)连接工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!-- 配置Redis主机名 -->
<property name="hostName" value="192.168.184.129"></property>
<!-- 配置Redis端口 -->
<property name="port" value="6379"></property>
<!-- 配置Redis密码 -->
<property name="password" value="lixing"></property>
<property name="poolConfig" ref="jedisPoolConfig"></property>
</bean>
<!-- 配置Redis模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
</bean>
在业务层中使用:
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
RedisTemplate<String, String> redis;
public String getValue(String key) {
ValueOperations<String, String> value = redis.opsForValue();
if(redis.hasKey(key)) {
System.out.println("从redis中取出:");
return value.get(key);
}else {
//模拟假设从MySQL中取出的数据
String str = "redisTemplate";
System.out.println("从MySQL中取出:");
value.set(key, str);
return str;
}
}
}
测试:
public class EmpTests {
@Autowired
RedisTemplate<String, String> redis;
@Test
public void test1() {
ClassPathXmlApplicationContext cpxac = new ClassPathXmlApplicationContext("spring.xml");
EmpService empservice = cpxac.getBean(EmpService.class);
String str = empservice.getValue("test3");
System.out.println(str);
}
}
通过RedisTemplate把数据保存到Redis时,所有的字符前都加了一串字符:
原因是,RedisTemplate默认会使用JdkSerializationRedisSerializer对数据进行序列化:
解决方法:在RedisTemplate 节点中为keySerializer和valueSerializer属性注入StringRedisSerializer类
<!-- 配置Redis模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<!-- key序列化默认JDK改为String -->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
<!-- value序列化默认JDK改为String -->
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
</bean>