org.springframework.data.redis.connection.RedisConnectionFactory Java Examples

The following examples show how to use org.springframework.data.redis.connection.RedisConnectionFactory. 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: RedisConfigure.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
 * 选择redis作为默认缓存工具
 *
 * @param redisConnectionFactory
 * @return
 */
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
    RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
            // 设置缓存的默认过期时间,也是使用Duration设置
            .entryTtl(Duration.ofDays(7))
            // 设置 key为string序列化
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringSerializer()))
            // 设置value为json序列化
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
            // 不缓存空值
            .disableCachingNullValues();
    return RedisCacheManager
            .builder(redisConnectionFactory)
            .transactionAware()
            .cacheDefaults(configuration)
            .build();
}
 
Example #2
Source File: RedisCacheConfiguration.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
	RedisTemplate<String, String> template = new RedisTemplate<>();
	template.setConnectionFactory(factory);

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

	// template.setKeySerializer(new StringRedisSerializer());
	// template.setValueSerializer(new JdkSerializationRedisSerializer());
	return template;
}
 
Example #3
Source File: CustomizedRedisCacheManager.java    From jim-framework with Apache License 2.0 6 votes vote down vote up
public CustomizedRedisCacheManager(
        RedisConnectionFactory connectionFactory,
        RedisOperations redisOperations,
        List<CacheItemConfig> cacheItemConfigList) {

    this(
            RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory),
            RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(30)),
            cacheItemConfigList
                    .stream()
                    .collect(Collectors.toMap(CacheItemConfig::getName,cacheItemConfig -> {
                        RedisCacheConfiguration cacheConfiguration =
                                RedisCacheConfiguration
                                        .defaultCacheConfig()
                                        .entryTtl(Duration.ofSeconds(cacheItemConfig.getExpiryTimeSecond()))
                                        .prefixKeysWith(cacheItemConfig.getName());
                        return cacheConfiguration;
                    }))
    );
    this.redisOperations=redisOperations;
    CacheContainer.init(cacheItemConfigList);

}
 
Example #4
Source File: RedisAutoConfig.java    From yue-library with Apache License 2.0 6 votes vote down vote up
/**
 * <p>支持FastJson进行Redis存储对象序列/反序列化
 * <p>https://github.com/alibaba/fastjson/wiki/%E5%9C%A8-Spring-%E4%B8%AD%E9%9B%86%E6%88%90-Fastjson
 */
@Bean
public RedisTemplate<String, Object> yueRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
	RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
	redisTemplate.setConnectionFactory(redisConnectionFactory);
	
	// 支持FastJson进行Redis存储对象序列/反序列化
	if (redisProperties.getRedisSerializerEnum() != RedisSerializerEnum.JDK) {
		redisTemplate.setDefaultSerializer(redisProperties.getRedisSerializerEnum().getRedisSerializer());
	}
	StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
	redisTemplate.setKeySerializer(stringRedisSerializer);
	redisTemplate.setHashKeySerializer(stringRedisSerializer);
	
	return redisTemplate;
}
 
Example #5
Source File: RedisCacheConfig.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * RedisTemplate配置
 * @param factory
 * @return
 */
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);
    //定义key序列化方式
    //RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型会出现异常信息;需要我们上面的自定义key生成策略,一般没必要
    //定义value的序列化方式
    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.setKeySerializer(redisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
}
 
Example #6
Source File: RedisConfig.java    From biliob_backend with MIT License 6 votes vote down vote up
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);

    // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
    Jackson2JsonRedisSerializer<Object> 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();
    return template;
}
 
Example #7
Source File: RedisUtils.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
/**
 * 查找匹配key
 * @param pattern key
 * @return /
 */
public List<String> scan(String pattern) {
    ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
    RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
    RedisConnection rc = Objects.requireNonNull(factory).getConnection();
    Cursor<byte[]> cursor = rc.scan(options);
    List<String> result = new ArrayList<>();
    while (cursor.hasNext()) {
        result.add(new String(cursor.next()));
    }
    try {
        RedisConnectionUtils.releaseConnection(rc, factory);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example #8
Source File: RedisHttpSessionConfigurationTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void qualifiedConnectionFactoryRedisConfig() {
	registerAndRefresh(RedisConfig.class, QualifiedConnectionFactoryRedisConfig.class);

	RedisIndexedSessionRepository repository = this.context.getBean(RedisIndexedSessionRepository.class);
	RedisConnectionFactory redisConnectionFactory = this.context.getBean("qualifiedRedisConnectionFactory",
			RedisConnectionFactory.class);
	assertThat(repository).isNotNull();
	assertThat(redisConnectionFactory).isNotNull();
	RedisOperations redisOperations = (RedisOperations) ReflectionTestUtils.getField(repository,
			"sessionRedisOperations");
	assertThat(redisOperations).isNotNull();
	assertThat(ReflectionTestUtils.getField(redisOperations, "connectionFactory"))
			.isEqualTo(redisConnectionFactory);
}
 
Example #9
Source File: MyRedisConfig.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * 自定义 RedisTemplate 序列化器
 */
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(
        RedisConnectionFactory redisConnectionFactory)
        throws UnknownHostException {
    RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
    template.setConnectionFactory(redisConnectionFactory);
    Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
    template.setDefaultSerializer(ser);
    return template;
}
 
Example #10
Source File: TracingRedisConnectionFactoryTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void delegatesClusterConnectionIfCluster() {
  RedisConnectionFactory connectionFactory = mock(RedisConnectionFactory.class);
  when(connectionFactory.getConnection()).thenReturn(mock(RedisClusterConnection.class));
  TracingRedisConnectionFactory tracingConnectionFactory = new TracingRedisConnectionFactory(
      connectionFactory,
      new TracingConfiguration.Builder(tracer).traceWithActiveSpanOnly(false).build());
  assertTrue(tracingConnectionFactory.getConnection() instanceof RedisClusterConnection);
}
 
Example #11
Source File: RedisTestConfig.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
@Bean
public RedisConnectionFactory connectionFactory() {
    RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class);
    RedisConnection connection = Mockito.mock(RedisConnection.class);
    Mockito.when(factory.getConnection()).thenReturn(connection);
    return factory;
}
 
Example #12
Source File: RedisTemplateConfiguration.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
	RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
		.entryTtl(Duration.ofHours(1));
	return RedisCacheManager
		.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
		.cacheDefaults(redisCacheConfiguration).build();
}
 
Example #13
Source File: CacheConfig.java    From uexam-mysql with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * spring boot redis默认序列化方式
 *
 * @return RedisTemplate
 */
@Bean
public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    redisTemplate.setKeySerializer(RedisSerializer.string());
    redisTemplate.setHashKeySerializer(RedisSerializer.string());
    redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
}
 
Example #14
Source File: RedisConfig.java    From spring-security with Apache License 2.0 5 votes vote down vote up
@Bean(name = "myRedisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    RedisSerializer<String> stringSerializer = new StringRedisSerializer();
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(stringSerializer);
    template.setKeySerializer(stringSerializer);
    template.afterPropertiesSet();
    return template;
}
 
Example #15
Source File: RedisConfiguration.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Bean("redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
	RedisTemplate<String, Object> template = new RedisTemplate<>();
	template.setConnectionFactory(factory);
	Jackson2JsonRedisSerializer<Object> 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.setValueSerializer(jackson2JsonRedisSerializer);
	template.setKeySerializer(stringRedisSerializer());
	template.afterPropertiesSet();
	return template;
}
 
Example #16
Source File: RedisConfig.java    From springBoot-study with Apache License 2.0 5 votes vote down vote up
/**
 * 设置数据存入 redis 的序列化方式,并开启事务
 * @param redisTemplate
 * @param factory
 */
private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
    //如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!  
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    // 开启事务
    redisTemplate.setEnableTransactionSupport(true);
    redisTemplate.setConnectionFactory(factory);
}
 
Example #17
Source File: BaseConfiguration.java    From common-project with Apache License 2.0 5 votes vote down vote up
/**
 * Redis模板
 *
 * @param connectionFactory 连接工厂
 * @return
 */
@Bean
public StringRedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
    StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(connectionFactory);
    GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
    stringRedisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
    stringRedisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
    return stringRedisTemplate;
}
 
Example #18
Source File: CachingConfig2.java    From Project with Apache License 2.0 5 votes vote down vote up
@Bean
public RedisConnectionFactory redisConnectionFactory() {
	JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
	connectionFactory.setHostName("192.168.198.129");
	connectionFactory.setPassword("123456");
	return connectionFactory;
}
 
Example #19
Source File: RedisAutoConfiguration.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Bean
@Primary
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

    // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

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

    RedisTemplate<String, Object> template = new RedisTemplate<>();
    // 配置连接工厂
    template.setConnectionFactory(factory);
    // 值采用json序列化
    template.setValueSerializer(serializer);
    // 使用StringRedisSerializer来序列化和反序列化redis的key值
    template.setKeySerializer(new StringRedisSerializer());
    // 设置hash key 和value序列化模式
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(serializer);
    template.afterPropertiesSet();

    return template;
}
 
Example #20
Source File: DefaultRedisCacheWriter.java    From black-shop with Apache License 2.0 5 votes vote down vote up
/**
 * @param connectionFactory must not be {@literal null}.
 * @param sleepTime         sleep time between lock request attempts. Must not be {@literal null}. Use {@link Duration#ZERO}
 *                          to disable locking.
 */
private DefaultRedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {

	Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
	Assert.notNull(sleepTime, "SleepTime must not be null!");

	this.connectionFactory = connectionFactory;
	this.sleepTime = sleepTime;
}
 
Example #21
Source File: MultiCacheAutoConfig.java    From api-gateway-old 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<>();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}
 
Example #22
Source File: RedisConnectionFactoryJavaConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void cloudRedisConnectionFactoryWithMaxPool() {
	ApplicationContext testContext =
			getTestApplicationContext(RedisConnectionFactoryConfigWithServiceConfig.class,
					createService("my-service"));

	RedisConnectionFactory connector = testContext.getBean("pool20Wait200", getConnectorType());
	RedisConnectionFactoryCloudConfigTestHelper.assertPoolProperties(connector, 20, 0, 200);
}
 
Example #23
Source File: RedisConfig.java    From JavaQuarkBBS 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 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.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
}
 
Example #24
Source File: BookReviewsApiIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public RedisConnectionFactory connectionFactory() {

    RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class);
    RedisConnection connection = Mockito.mock(RedisConnection.class);
    Mockito.when(factory.getConnection()).thenReturn(connection);

    return factory;
}
 
Example #25
Source File: OAuth2Config.java    From Auth-service with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
        RedisConnectionFactory redisConnectionFactory)
        throws UnknownHostException {
    RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}
 
Example #26
Source File: RedisConfiguration.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
@Bean
public ShopRedisTemplate shopRedisTemplate(
        RedisConnectionFactory redisConnectionFactory) {
    ShopRedisTemplate template = new ShopRedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}
 
Example #27
Source File: MyTemplate.java    From BigDataArchitect with Apache License 2.0 5 votes vote down vote up
@Bean
public StringRedisTemplate ooxx(RedisConnectionFactory fc){

    StringRedisTemplate tp = new StringRedisTemplate(fc);

    tp.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
    return  tp ;
}
 
Example #28
Source File: RedisConfig.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 配置使用注解的时候缓存配置,默认是序列化反序列化的形式,加上此配置则为 json 形式
 */
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
    // 配置序列化
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
    RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

    return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
}
 
Example #29
Source File: RedisConfiguration.java    From spring-boot-with-multi-redis with MIT License 5 votes vote down vote up
@Primary
@Bean(name = "userRedisConnectionFactory")
public RedisConnectionFactory userRedisConnectionFactory() {
    JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
    redisConnectionFactory.setHostName(userRedisProperty.getHost());
    redisConnectionFactory.setPort(userRedisProperty.getPort());
    redisConnectionFactory.setDatabase(userRedisProperty.getDatabase());
    return redisConnectionFactory;
}
 
Example #30
Source File: SpringCloudRestServerIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public RedisConnectionFactory connectionFactory() {
    
    RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class);
    RedisConnection connection = Mockito.mock(RedisConnection.class);
    Mockito.when(factory.getConnection()).thenReturn(connection);

    return factory;
}