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);
}
}