Redis之Java调用哨兵

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

    最近在使用Redis,记录下。

1.加入依赖

    List-1  只是给出与Redis有关的依赖,其它的spring依赖就略


    org.springframework.data
    spring-data-redis
    1.8.14.RELEASE


    redis.clients
    jedis
    2.9.0

2.spring的xml配置

2.1 哨兵配置

    List-2 如何搭建哨兵机制的集群,在此处就略,不描述了


    
    
        
            192.168.0.107:26481
            192.168.0.107:26482
            192.168.0.107:26483
        
    

2.2 池pool配置

    List-3


    
    
    
    

2.3 工厂Factory配置

    List-4


    
    
    
    
    

2.4 redisTemplate配置

    List-5


    
    
        
    
    
        
    

3. 测试

3.1 Redis缓存对象

    List-6

/**
 * @author [email protected] 2018-08-23 23:01
 * @version 1.0
 * @since 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring.xml"})
public class MyRedisTestBase {

}

    List-7 由于我们使用了JDK的Serializable作为序列化,所以对象一定要实现Serializable接口,不然会报错的

/**
 * @author [email protected] 2018-09-12 20:51
 * @version 1.0
 * @since 1.0
 */
public class SerializableRedisTemplate extends MyRedisTestBase {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test1() {
        Address address = new Address();
        address.setCode(getRandomUUID());
        address.setName(getRandomUUID());

        Person person = new Person();
        person.setAge(12);
        person.setName("mjduan");
        person.setAddresses(Arrays.asList(address));

        redisTemplate.opsForValue().set(person.getName(), person);

        Serializable serializable = redisTemplate.opsForValue().get(person.getName());
        Person newPerson = (Person) serializable;
        System.out.println(newPerson);
    }
     
    private String getRandomUUID() {
        return UUID.randomUUID().toString();
    }    
}

3.2 config set

    List-8 设置maxmemory的值

    @Test
    public void test2() {
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        //maxmemory的值,单位最好是bytes,因为redis.conf里面就有注释
        connection.setConfig("maxmemory", "1mb");

        List maxmemory = connection.getConfig("maxmemory");
        assertEquals(2, maxmemory.size());
        assertEquals(1L * 1024 * 1024, Long.valueOf(maxmemory.get(1)).longValue());
    }

    在redis命令里面查看结果,如下List-9:

    List-9 可以看到List-8中设置的1mb生效了,1*1024*1024=1048576

127.0.0.1:6379[1]> config get maxmemory
1) "maxmemory"
2) "1048576"
127.0.0.1:6379[1]> config get maxmemory
1) "maxmemory"
2) "1048576"
127.0.0.1:6379[1]> select 7
OK
127.0.0.1:6379[7]> config get maxmemory
1) "maxmemory"
2) "1048576"
127.0.0.1:6379[7]>

    如List-9中所示,我们虽然在List-4中设置的database是7,但是从List-9中可以看出,通过config set设置的值是全局生效了。在database7中得到的maxmemory是1048576,在database1中得到的maxmemory也是1048576。

转载于:https://my.oschina.net/u/2518341/blog/2050495

你可能感兴趣的:(Redis之Java调用哨兵)