Redis篇7-客户端与Java操作

可视化客户端软件

  • 官方地址:https://redisdesktop.com
  • 百度云地址:https://pan.baidu.com/s/1ctCfspajPF--jGUzBsu7pw
  • 打开redisdesktop,新建连接,输入地址和端口,测试连接,OK
  • 连不上可能的原因
    • redis.conf中请注掉修改默认的bind(只允许本机连接),或者添加新的ip白名单
    • 如果粗暴的注掉默认bind,请同时修改protected-mode为no
    • 正式环境建议添加白名单,这样安全且不用考虑redis密码
    • 还连不上的话,检查防火墙。。
  • 连接后,就可以很方便的查看和设置缓存数据了

Jedis操作

  • 引入Jedis依赖
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <!-- <version>2.9.0</version> -->
    </dependency>
    
  • 快速测试Java程序连接redis
    @Test
    public void contextLoads() {
    	String host = "192.168.1.12";
    	int port = 6379;
    	Jedis jedis = new Jedis(host, port);
    	System.out.println(jedis.ping()); //PONG
    }
    
  • 查看jedis对象方法列表可以发现,全部和官方的redis命令一致

springboot 与 RedisTemplate

  • springboot中使用spring-data-redis操作redis及其简单

  • 引入目标starter

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  • 看一下对应的 RedisAutoConfiguration 类

    @Configuration
    @ConditionalOnClass(RedisOperations.class)
    @EnableConfigurationProperties(RedisProperties.class)
    @Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
    public class RedisAutoConfiguration {
    
    	@Bean
    	@ConditionalOnMissingBean(name = "redisTemplate")
    	public RedisTemplate<Object, Object> redisTemplate(
    			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    		RedisTemplate<Object, Object> template = new RedisTemplate<>();
    		template.setConnectionFactory(redisConnectionFactory);
    		return template;
    	}
    
    	@Bean
    	@ConditionalOnMissingBean
    	public StringRedisTemplate stringRedisTemplate(
    			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    		StringRedisTemplate template = new StringRedisTemplate();
    		template.setConnectionFactory(redisConnectionFactory);
    		return template;
    	}
    
    }
    

    可以看出,已经自动注入了RedisTemplate和最常用的StringRedisTemplate
    类比JdbcTemplate,使用他们就可以方便的操作Redis。

  • 添加相应的Properties配置

    spring:
      redis:
        host: 192.168.1.12
        port: 6379
    
  • 测试RedisTemplate

    • 同Jedis,可以获得官方命令方法列表,比如set、append
    • 字符串操作
      @Test
      public void test0() {
      	ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
      	opsForValue.set("k1", "v1");
      	System.out.println(opsForValue.get("k1"));
      	opsForValue.append("k1", "+v1");
      	System.out.println(opsForValue.get("k1"));
      }
      
    • 保存对象
      @Test
      public void test_obj() {
      	ValueOperations<Object, Object> opsForValue = redisTemplate.opsForValue();
      	TestBean testBean = new TestBean(1, "obj1");
      	opsForValue.set("obj1", testBean);
      	System.out.println(testBean);
      	System.out.println(opsForValue.get("obj1"));
      }
      
    • 保存对象到redis服务器问题1
      • 上面保存对象后,redis中存的对应键值内容类似乱码,虽然通过RedisTemplate获取结果没差,但是可读性差
        xacxedx00x05tx00x04obj1
        
      • 这是因为使用了JDK默认的序列化机制(Serializable)
        if (defaultSerializer == null) {
        
        	defaultSerializer = new JdkSerializationRedisSerializer(
        			classLoader != null ? classLoader : this.getClass().getClassLoader());
        }
        
        可以自行提供RedisTemplate Bean,修改序列化方式为为Json序列化
    • 修改RedisTemplate序列化方式为Json
      • 方式1:手工保存,即set之前自行将对象转为JSON串(优点:专注使用stringRedisTemplate)
        @Test
        public void test_obj_2() {
        	ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        	String key = "obj2";
        	TestBean value = new TestBean(2, "obj2");
        	opsForValue.set(key, MyJsonUtil.obj2JsonStr(value));
        	System.out.println(opsForValue.get(key));
        }
        
      • 方式2:自行提供RedisTemplate Bean,修改其defaultSerializer
        @Configuration
        public class MyComponentBeansConfig {
        	private final Logger logger = LoggerFactory.getLogger(MyComponentBeansConfig.class);
        	
        	//修改 RedisTemplate<Object, Object> 序列化方式为 Json
        	@Bean
        	public RedisTemplate<Object, Object> redisTemplate(
        			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        		logger.info(">> inject my RedisTemplate");
        		RedisTemplate<Object, Object> template = new RedisTemplate<>();
        		template.setConnectionFactory(redisConnectionFactory);
        		template.setDefaultSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        		return template;
        	}
        }
        
原文地址:https://www.cnblogs.com/noodlerkun/p/11555442.html