springboot使用redis客户端redistemplate

          redis客户端有多种,常见有jedis,redisson,redistemplate,而redistemplate其实是对jedis的封装,本文着重讲使用方法,关于原理,后续再研究。

          第一步:添加依赖jar

        <!-- redis -->
      <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-redis</artifactId>
      </dependency>
      <dependency>
         <groupId>redis.clients</groupId>
         <artifactId>jedis</artifactId>
      </dependency>

       第二步:配置redis,application.properties里面写上redis连接信息

#集群
spring.redis.cluster.nodes=131.252.10.133:6379,131.252.10.133:6380,131.252.10.134:6379,131.252.10.134:6380,131.252.10.135:6379,131.252.10.135:6380
spring.redis.pool.max-active=300
spring.redis.database=0
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=100
spring.redis.pool.min-idle=20
spring.redis.timeout=60000
spring.redis.password=test1234

       第三步:Redis配置文件RedisConfig.java

/**
 * 
 */
package com.figo.springboottest.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author figo
 *
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
	 /**
     * 选择redis作为默认缓存工具
     * @param redisTemplate
     * @return
     */
//    @Bean
//    public CacheManager cacheManager(RedisTemplate redisTemplate) {
//        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//        return rcm;
//    }
    //springboot 2.3.2新版本后改成下面这种方式
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
    	RedisCacheManager rcm = RedisCacheManager.builder(factory).build();
    	return rcm;
    }
    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
 
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
 
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
 
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL,  com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
 
        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
 
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
 
        return template;
    }
}

       第四步:单元测试RedisTest.java

package com.figo.springboottest;

import java.util.concurrent.TimeUnit;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;
import org.junit.Test;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
	@Autowired
	private RedisTemplate redisTemplate;

	@Test
	public void testRedisTemplate() throws Exception {
		ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
		valueOperations.set("key1", "test1", 1800, TimeUnit.SECONDS); // 新增, 设置失效时间30分钟
		valueOperations.set("key2", "test2"); // 存在的话就是修改
		Object val1 = valueOperations.get("key1");
		System.out.println("key1获取到的值="+val1);
		Object val2 = valueOperations.get("key2");
		System.out.println("key2获取到的值="+val2);
		redisTemplate.delete("key2");
		val2 = valueOperations.get("key2");
		System.out.println("key2删除后获取到的值="+val2);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值