springboot2之系統架構基礎(五) springboot整合redis

step1 導入pom配置

<!-- spring redis -->
    	<dependency>  
              <groupId>org.springframework.boot</groupId>  
              <artifactId>spring-boot-starter-redis</artifactId>  
              <version>1.4.3.RELEASE</version>  
        </dependency> 

step2 yml配置redis集羣

## Spring配置:
spring: 
  http: 
    encoding:
      charset: UTF-8 
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    default-property-inclusion: NON_NULL      
  redis:   
    pool: 
      min-idle: 100
      max-idle: 100
      max-wait: -1
      max-active: 1000
    timeout: 6000  
    cluster: 
      max-redirects: 1000
      nodes: 
          - 192.168.128.12:7001
          - 192.168.128.12:7002
          - 192.168.128.12:7003
          - 192.168.128.12:7004
          - 192.168.128.12:7005
          - 192.168.128.12:7006 

properties 配置

spring.redis.cluster.nodes=192.168.2.124:7001,192.168.2.124:7002,192.168.2.124:7003,192.168.2.124:7004,192.168.2.124:7005,192.168.2.124:7006
spring.redis.timeout=0
# jedis pool configure
spring.redis.pool.max-total=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0

注意:是spring下的redis

step3 配置redis 的 RedisTemplate 對象

@Configuration
public class MyRedisConfiguration {

	@Bean
	public RedisTemplate<String, Object> initRedisTemplate(RedisConnectionFactory redisConnectionFactory){
		
		
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		
		return redisTemplate;
	}
	
}

step4  測試操作集羣元素

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTests {

    private static Logger LOGGER = LoggerFactory.getLogger(ApplicationTests.class);    
    @Autowired  
    RedisTemplate<String, String> redisTemplate;  
      
    /**
     * <B>方法名稱:</B>測試redis<BR>
     * <B>概要說明:</B><BR>
     */
    @Test  
    public void redisTest() {  
        String key = "redisTestKey";  
        String value = "I am test value";  
       
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();  
         System.err.println("---------------");
        //數據插入測試:  
        opsForValue.set(key, value);  
        String valueFromRedis = opsForValue.get(key);  
        LOGGER.info("redis value after set: {}", valueFromRedis);  
          
        //數據刪除測試:  
        redisTemplate.delete(key);  
        valueFromRedis = opsForValue.get(key);  
        LOGGER.info("redis value after delete: {}", valueFromRedis);  
    }  
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章