RedisTemplate的两种注入方式:xml+注解

RedisTemplate注入
官网上只给出了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:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true"/>
  <!-- redis template definition -->
  <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnectionFactory"/>
  ...

</beans>

解读xml 就是bean:redisTemplate把bean:jedisConnectionFactory 作为参数,然后,交给spring容器初始化。
对应注解如下:

//springBoot会扫描该注解中的bean,即声明bean配置
@Configuration
public class RedisConfig {
    //1.声明bean:redisTemplate
    //2.RedisConnectionFactory redisConnectionFactory等于 p:connection-factory-ref
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate=new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
//        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
 }


yml如下:

  redis:
    host: xx.xx.x.xxx
    port: 6379
    password: redis@123

    jedis:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0
    timeout: 5000ms

测试

//注意:测试类必须继承SpringBoot自动生成的测试基类。即启动类对应的测试类
public class  UserServiceTest extends StartTest {
    static Log log = LogFactory.getLog(UserServiceTest.class);
    
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void redisTest() throws Exception {
        log.debug("start==================================");
        redisTemplate.boundListOps("namelist1").rightPush("刘备");
        redisTemplate.boundListOps("namelist1").rightPush("关羽");
        redisTemplate.boundListOps("namelist1").rightPush("张飞");
        
        List list = redisTemplate.boundListOps("namelist1").range(0, 10);
        System.out.println(list);
    }
}
发布了21 篇原创文章 · 获赞 6 · 访问量 9315

猜你喜欢

转载自blog.csdn.net/qq1032350287/article/details/103886451
今日推荐