前面我们已经介绍了Redis的一些基本操作,以及在java中如何使用,但是我们在Spring中如何使用呢?这篇博客就带着大家在Spring中使用Redis
1.首先在Spring的大框架下,如何使用呢?Spring中Spring Date进行扩展,我们在Spring中导入spring-data-redis引入这个jar包之后,就会给我们扩展出一个RedisTemplate对象,RedisTemplate封装了一些连接,对象的操作,释放等.和JdbcTemplate相似。
2.追加连接工厂配置,注入给RedisTemplate
<bean id="redisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="localhost"></property>
<property name="port" value="6379"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="redisFactory"></property>
<!--让key走String不走JDK的OBJECT序列化器-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
</bean>
3.测试连接使用
@Test
public void test6() throws Exception {
ApplicationContext app = new
ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate template = app.getBean("redisTemplate",RedisTemplate.class);
template.opsForValue().set("age","18");
User user = new User(1,"张杰","8848");
template.opsForValue().set("user",user);
}
程序运行前后对比
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200515114320427.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzIzNTE0Nw==,size_16,color_FFFFFF,t_70)
RedisTemplate还封装了很多方法,这里就不一一举例了