org.springframework.data.redis.core.RedisTemplate Java Examples

The following examples show how to use org.springframework.data.redis.core.RedisTemplate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedisConfUtils.java    From storm_spring_boot_demo with MIT License 7 votes vote down vote up
public static RedisTemplate buildRedisTemplate(byte[] redisProperties){
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(
            RedisConfUtils.getClusterConfiguration(
                    (RedisProperties) Serializer.INSTANCE.deserialize(redisProperties)));
    RedisTemplate<String, Long> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory);
    jedisConnectionFactory.afterPropertiesSet();

    GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    redisTemplate.setKeySerializer(stringRedisSerializer);
    redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
    redisTemplate.setHashKeySerializer(stringRedisSerializer);
    redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
}
 
Example #2
Source File: RedisCacheConfig.java    From shield-ratelimter with Apache License 2.0 6 votes vote down vote up
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);

    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(mapper);

    template.setValueSerializer(serializer);
    //使用StringRedisSerializer来序列化和反序列化redis的key值
    template.setKeySerializer(new StringRedisSerializer());
    template.afterPropertiesSet();
    LOGGER.info("Springboot RedisTemplate 加载完成");
    return template;
}
 
Example #3
Source File: RedisConfig.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Bean(name = "redisTemplate")
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    //序列化
    FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
    // value值的序列化采用fastJsonRedisSerializer
    template.setValueSerializer(fastJsonRedisSerializer);
    template.setHashValueSerializer(fastJsonRedisSerializer);
    // 全局开启AutoType,这里方便开发,使用全局的方式
    ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    // 建议使用这种方式,小范围指定白名单
    // ParserConfig.getGlobalInstance().addAccept("com.dxj.domain");
    // key的序列化采用StringRedisSerializer
    template.setKeySerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}
 
Example #4
Source File: RedisConfig.java    From springboot_cwenao with MIT License 6 votes vote down vote up
@Bean(name="redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {

    RedisTemplate<String, String> template = new RedisTemplate<>();


    RedisSerializer<String> redisSerializer = new StringRedisSerializer();

    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    template.setConnectionFactory(factory);
    //key序列化方式
    template.setKeySerializer(redisSerializer);
    //value序列化
    template.setValueSerializer(jackson2JsonRedisSerializer);
    //value hashmap序列化
    template.setHashValueSerializer(jackson2JsonRedisSerializer);

    return template;
}
 
Example #5
Source File: RedisConfig.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
@Bean
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
{
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);

    FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    serializer.setObjectMapper(mapper);

    template.setValueSerializer(serializer);
    // 使用StringRedisSerializer来序列化和反序列化redis的key值
    template.setKeySerializer(new StringRedisSerializer());
    template.afterPropertiesSet();
    return template;
}
 
Example #6
Source File: RedisConfig.java    From dubbo-spring-boot-learning with MIT License 6 votes vote down vote up
/**
 * RedisTemplate配置,使用Jackson2JsonRedisSerializer作为序列化器
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, String> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);

    // 使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
}
 
Example #7
Source File: RedisConfig.java    From spring-boot-seckill with GNU General Public License v2.0 6 votes vote down vote up
/**
    * 序列化Java对象
    * @Author  科帮网
    * @param factory
    * @return  RedisTemplate<Object, Object>
    * @Date	2017年8月13日
    * 更新日志
    * 2017年8月13日 科帮网  首次创建
    *
    */
   @SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
   public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
       RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
       template.setConnectionFactory(connectionFactory);
       //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
       Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
       ObjectMapper mapper = new ObjectMapper();
       mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
       mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
       serializer.setObjectMapper(mapper);
       template.setValueSerializer(serializer);
       template.setKeySerializer(new StringRedisSerializer());
       template.afterPropertiesSet();
       return template;
   }
 
Example #8
Source File: RedisConfig.java    From notes with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
        throws UnknownHostException {

    RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
    template.setConnectionFactory(redisConnectionFactory);

    ObjectMapper om = new ObjectMapper();

    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    RedisSerializer redisSerializer = fastJson2RedisSerializer();

    template.setValueSerializer(redisSerializer);
    template.setKeySerializer(new StringRedisSerializer());
    template.afterPropertiesSet();

    return template;

}
 
Example #9
Source File: RedisConfig.java    From jeesupport with MIT License 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean( name = "redisTemplate" )
@Primary
public < T > RedisTemplate< String, T > redisTemplate( RedisConnectionFactory _rcf ){
    RedisTemplate< String, T > template = new RedisTemplate<>();

    //使用fastjson序列化
    // value值的序列化采用fastJsonRedisSerializer
    template.setValueSerializer( new FastJsonRedisSerializer<T>() );
    template.setHashValueSerializer( new FastJsonRedisSerializer<T>() );
    // key的序列化采用StringRedisSerializer
    template.setKeySerializer( new FastJsonRedisSerializer<T>() );
    template.setHashKeySerializer( new FastJsonRedisSerializer<T>() );

    template.setConnectionFactory( _rcf );
    // 开启事务
    template.setEnableTransactionSupport( true );
    template.afterPropertiesSet();

    return template;
}
 
Example #10
Source File: DataRedisContextInitializer.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    Environment env = applicationContext.getEnvironment();
    applicationContext.getBeanFactory().addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter() {
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof RedisTemplate) {
                RedisTemplate redisTemplate = (RedisTemplate)bean;
                // do cache
                redisTemplate.opsForValue();
                redisTemplate.opsForList();
                redisTemplate.opsForSet();
                redisTemplate.opsForZSet();
                redisTemplate.opsForGeo();
                redisTemplate.opsForHash();
                redisTemplate.opsForHyperLogLog();
                createProxyHandlers(redisTemplate);
            }
            return bean;
        }
    });
}
 
Example #11
Source File: ShiroBaseConfigure.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/***
 * 密码凭证匹配器,采用redis记录重试次数,超过指定次数则不允许登录
 * @return
 */
@Bean
@Conditional(RedisEnableCondition.class)
public CredentialsMatcher retryLimitHashedCredentialsMatcher(RedisTemplate<Object, Object> redisTemplate) {
    return credentialsMatcher(redisTemplate);

}
 
Example #12
Source File: RedisConfig.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public RedisTemplate<String, Object> redisTemplate() {
    final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
    template.setConnectionFactory(jedisConnectionFactory());
    template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
    return template;
}
 
Example #13
Source File: RedisConfig.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
 * @param redisConnectionFactory
 * @return
 */
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);

    // redis value使用的序列化器
    template.setValueSerializer(new KryoRedisSerializer<>(Object.class));
    // redis key使用的序列化器
    template.setKeySerializer(new StringRedisSerializer());

    template.afterPropertiesSet();
    return template;
}
 
Example #14
Source File: RedisIdGenerator.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
/**
 * @param redisTemplate the redisTemplate to set
 */
// 目前AutoWired 不起作用(没有用spring来托管),因此在getInstance时进行自动获取
@Autowired(required = false)
@Qualifier(value = "redisTemplate")
public void setRedisTemplate(RedisTemplate<?, ?> redisTemplate) {
	this.redisTemplate = redisTemplate;
}
 
Example #15
Source File: RedisConfig.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
	StringRedisTemplate template = new StringRedisTemplate(factory);
	Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
			Object.class);
	ObjectMapper om = new ObjectMapper();
	om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
	om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
	jackson2JsonRedisSerializer.setObjectMapper(om);
	template.setKeySerializer(myStringSerializer);
	template.setHashKeySerializer(myStringSerializer);
	template.setValueSerializer(jackson2JsonRedisSerializer);
	template.afterPropertiesSet();
	return template;
}
 
Example #16
Source File: CasbinRedisWatcherAutoConfiguration.java    From casbin-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnBean(RedisTemplate.class)
@ConditionalOnMissingBean
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public Watcher redisWatcher(StringRedisTemplate stringRedisTemplate, Enforcer enforcer) {
    RedisWatcher watcher = new RedisWatcher(stringRedisTemplate);
    enforcer.setWatcher(watcher);
    logger.info("Casbin set watcher: {}", watcher.getClass().getName());
    return watcher;
}
 
Example #17
Source File: RedisConfiguration.java    From daming with Apache License 2.0 5 votes vote down vote up
@ConditionalOnMissingBean(SmsVerificationRepository.class)
@Bean(name = "redisSmsVerificationStore")
public RedisSmsVerificationRepository redisSmsVerificationStore(@Qualifier("smsVerificationRedisTemplate")
                                                                        RedisTemplate<String, SmsVerification> redisTemplate,
                                                                DeleteFromRedis deleteFromRedis) {
    RedisSmsVerificationRepository bean = new RedisSmsVerificationRepository(redisTemplate, deleteFromRedis);
    return bean;
}
 
Example #18
Source File: RedisCache.java    From yfshop with Apache License 2.0 5 votes vote down vote up
/**
     * Get cached query result from redis
     *
     * @param key
     * @return
     */
    @Override
    public Object getObject(Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            ValueOperations opsForValue = redisTemplate.opsForValue();
            logger.debug("Get cached query result from redis");
//            System.out.println("****" + opsForValue.get(key).toString());
            return opsForValue.get(key);
        } catch (Throwable t) {
            logger.error("Redis get failed, fail over to db", t);
            return null;
        }
    }
 
Example #19
Source File: RedisDao.java    From redis-admin with Apache License 2.0 5 votes vote down vote up
public void delRedisKeys(String serverName, int dbIndex, String deleteKeys) {
	RedisTemplate<String, Object> redisTemplate = redisTemplateFactory.getRedisTemplate(serverName);
	redisConnectionDbIndex.set(dbIndex);
	String[] keys = deleteKeys.split(",");
	redisTemplate.delete(Arrays.asList(keys));
	return;
}
 
Example #20
Source File: RedisCacheConfig.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Bean
public RedisCacheManager cacheManager(RedisTemplate templateRedis) {
    RedisCacheManager redisCacheManager = new RedisCacheManager(templateRedis);
    redisCacheManager.setTransactionAware(true);
    redisCacheManager.setLoadRemoteCachesOnStartup(true);
    redisCacheManager.setUsePrefix(true);

    return redisCacheManager;
}
 
Example #21
Source File: RedisAutoConfig.java    From yue-library with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
@ConditionalOnBean({ RedisTemplate.class, StringRedisTemplate.class })
public Redis redis(@Qualifier("yueRedisTemplate") RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) {
	log.info("【初始化配置-Redis客户端】配置项:{},默认使用 {} 进行Redis存储对象序列/反序列化。Bean:Redis ... 已初始化完毕。", 
			RedisProperties.PREFIX,
			ClassUtils.getClassName(RedisSerializerEnum.class, false).concat(".JDK"));
	return new Redis(redisTemplate, stringRedisTemplate);
}
 
Example #22
Source File: UserTokenServiceImpl.java    From uexam-mysql with GNU Affero General Public License v3.0 5 votes vote down vote up
@Autowired
public UserTokenServiceImpl(UserTokenMapper userTokenMapper, UserService userService, SystemConfig systemConfig, CacheConfig cacheConfig, RedisTemplate<String, Object> redisTemplate) {
    super(userTokenMapper);
    this.userTokenMapper = userTokenMapper;
    this.userService = userService;
    this.systemConfig = systemConfig;
    this.cacheConfig = cacheConfig;
    this.redisTemplate = redisTemplate;
}
 
Example #23
Source File: TcpChannelMsgManage.java    From jt809-tcp-server with MIT License 5 votes vote down vote up
@Autowired
public void setRedisTemplate(RedisTemplate redisTemplate) {
    RedisSerializer stringSerializer = new StringRedisSerializer();
    RedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();
    redisTemplate.setKeySerializer(stringSerializer);
    redisTemplate.setValueSerializer(stringSerializer);
    redisTemplate.setHashKeySerializer(stringSerializer);
    redisTemplate.setHashValueSerializer(jdkSerializer);
    redisTemplate.afterPropertiesSet();
    this.redisTemplate = redisTemplate;
}
 
Example #24
Source File: RedisLuaRateLimiter.java    From api-boot with Apache License 2.0 5 votes vote down vote up
public RedisLuaRateLimiter(Long globalQPS, RateLimiterConfigCentre rateLimiterConfigCentre, RedisTemplate redisTemplate) {
    super(globalQPS, rateLimiterConfigCentre);
    this.redisTemplate = redisTemplate;
    this.redisScript = getRedisScript();

    Assert.notNull(redisTemplate, "No RedisTemplate implementation class was found.");
    Assert.notNull(redisScript, "Unable to load Lua script.");
}
 
Example #25
Source File: Application.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@code RedisTemplate} object for executing operations with 
 * Redis.
 * 
 * @return  The object of {@code RedisTemplate}.
 */
@Bean
public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(jedisConnectionFactory());
    return template;
}
 
Example #26
Source File: DataRedisContextInitializer.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void createProxyHandler(RedisTemplate redisTemplate, Class clazz, String name) {
    try {
        Field field = ReflectionUtils.findField(RedisTemplate.class, name, clazz);
        ReflectionUtils.makeAccessible(field);
        Object object = ReflectionUtils.getField(field, redisTemplate);
        DataRedisProxyHandler handler = new DataRedisProxyHandler(object);
        Object proxy = Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class[] {clazz}, handler);
        field.set(redisTemplate, proxy);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: RedisCache.java    From poseidon with Apache License 2.0 5 votes vote down vote up
/**
 * Remove cached query result from redis
 * @param key
 * @return
 */
@Override
@SuppressWarnings("unchecked")
public Object removeObject(Object key) {
	try {
		RedisTemplate redisTemplate = getRedisTemplate();
		redisTemplate.delete(key);
		logger.debug("Remove cached query result from redis");
	}
	catch (Throwable t) {
		logger.error("Redis remove failed", t);
	}
	return null;
}
 
Example #28
Source File: RedisConfig.java    From JavaQuarkBBS with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    //设置缓存过期时间
    //rcm.setDefaultExpiration(60);//秒
    return rcm;
}
 
Example #29
Source File: MissingCondition.java    From java-master with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    try {
        context.getBeanFactory().getBean(RedisTemplate.class);
        return false;
    } catch (NoSuchBeanDefinitionException e) {
        return true;
    }
}
 
Example #30
Source File: RedisConfig.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
        RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();

    //使用fastjson序列化
    FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<Object>(Object.class);
    // value值的序列化采用fastJsonRedisSerializer
    template.setValueSerializer(fastJsonRedisSerializer);
    // key的序列化采用StringRedisSerializer
    template.setKeySerializer(new StringRedisSerializer());
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}