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

The following examples show how to use org.springframework.data.redis.core.RedisOperations. 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: RedisTemplateTransactional.java    From sdmq with Apache License 2.0 7 votes vote down vote up
@Test
    public void test2() {
        System.out.println(11);
        List<Object> results = (List<Object>) redisTemplate.execute(new SessionCallback<List<Object>>() {
            @SuppressWarnings({"rawtypes", "unchecked"})
            public List<Object> execute(RedisOperations operations) {
                operations.multi();
                //new Jedis().multi();
                operations.opsForValue().set("abb", "233332");
                if (true) {
                    throw new eeee("xx");
                }
                operations.opsForValue().set("abb", "2");
//                operations.opsForValue().set("11", "22");
//                operations.opsForValue().get("11");
//                operations.opsForList().leftPush("aaa", 1);
//                operations.opsForList().range("aaa", 0l, 1l);
//                operations.opsForSet().add("bbbb", 12);
//                operations.opsForSet().members("bbbb");
                return operations.exec();
            }
        });
        for (Object o : results) {
            System.out.println(o);
        }
    }
 
Example #2
Source File: FollowServiceImpl.java    From MyCommunity with Apache License 2.0 6 votes vote down vote up
@Override
public void unfollow(int userId, int entityType, int entityId) {

    String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
    String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);

    redisTemplate.execute(new SessionCallback() {
        @Override
        public Object execute(RedisOperations redisOperations) throws DataAccessException {

            redisOperations.multi();
            // 自己的关注列表
            redisTemplate.opsForZSet().remove(followeeKey, entityId, System.currentTimeMillis());
            // 被关注对象的粉丝列表
            redisTemplate.opsForZSet().remove(followerKey, userId, System.currentTimeMillis());

            return redisOperations.exec();
        }
    });

}
 
Example #3
Source File: VoteDataInspect.java    From sanshanblog with Apache License 2.0 6 votes vote down vote up
/**
 * 从数据库恢复数据
 */
public void inspectDataConsistency() {
    if(checkIsNeedRollback()) {
        Long initTime = System.currentTimeMillis();
        //进行点赞数据的事务完整性检查
        log.info("投票数据进行数据回滚");
        List<BlogVoteDO> blogVoteDOS = blogVoteMapper.selectAll();
        List<IpBlogVoteDO> ipBlogVoteDOS = ipBlogVoteMapper.selectAll();
        //开启事务
        SessionCallback sessionCallback = new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.multi();
                rollbackData(blogVoteDOS, ipBlogVoteDOS);
                return redisOperations.exec();
            }
        };
        //执行
        redisTemplate.execute(sessionCallback);
        log.info("从数据库中回滚投票数据的完成 耗时:{}ms", System.currentTimeMillis() - initTime);
    }else {

    }
}
 
Example #4
Source File: UEditorFileDataInspect.java    From sanshanblog with Apache License 2.0 6 votes vote down vote up
/**
 *
 从数据库恢复数据
 */
public void inspectDataConsistency() {
    if(checkIsNeedRollback()) {
        //数据库与BlogIdGenerate的事物完整性检查
        Long initTime = System.currentTimeMillis();
        log.info("ueditor的文件数据从数据库中回滚");
        //开启事务
        SessionCallback sessionCallback = new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.multi();
                rollbackData();
                return redisOperations.exec();
            }
        };
        //事务执行
        redisTemplate.execute(sessionCallback);
        log.info("ueditor上传文件数据中的数据回滚完成 耗时:{}ms", System.currentTimeMillis() - initTime);
    }
}
 
Example #5
Source File: RedisSignUpRepository.java    From flex-poker with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void storeSignUpInformation(UUID aggregateId, String username, UUID signUpCode) {
    var signUpCodeKey = SIGN_UP_CODE_NAMESPACE + signUpCode.toString();

    redisTemplate.execute(new SessionCallback<List<Object>>() {
        @Override
        public List<Object> execute(RedisOperations operations) throws DataAccessException {
            operations.multi();
            operations.opsForHash().put(signUpCodeKey, "username", username);
            operations.opsForHash().put(signUpCodeKey, "aggregateid",
                    aggregateId.toString());
            operations.expire(signUpCodeKey, EXPIRATION_IN_MINUTES, TimeUnit.MINUTES);
            return redisTemplate.exec();
        }
    });
}
 
Example #6
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 #7
Source File: AppTest.java    From Breakpoint-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testRedisMap() {
    Object object = redisTemplate.execute(new SessionCallback() {
        @Override
        public Object execute(RedisOperations operations) throws DataAccessException {
            operations.multi();
            operations.opsForValue().get("test");
            operations.delete("test");
            operations.opsForValue().set("test", "6");
            List<String> rs = operations.exec();
            System.out.println(" rs:" + rs.toString());
            return rs;
        }
    });
    List<Object> strings = (List<Object>) object;
    for (Object str : strings) {
        System.err.println(str.toString());
    }
}
 
Example #8
Source File: RedisSignUpRepository.java    From flex-poker with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void saveSignUpUser(SignUpUser signUpUser) {
    final var signUpUserKey = SIGN_UP_USER_NAMESPACE + signUpUser.getAggregateId();
    final var signUpUserMap = Map.of(
            "username", signUpUser.getUsername(),
            "email", signUpUser.getEmail(),
            "aggregateId", signUpUser.getAggregateId().toString(),
            "signUpCode", signUpUser.getSignUpCode().toString(),
            "confirmed", String.valueOf(signUpUser.isConfirmed()),
            "encryptedPassword", signUpUser.getEncryptedPassword());

    redisTemplate.execute(new SessionCallback<List<Object>>() {
        @Override
        public List<Object> execute(RedisOperations operations) throws DataAccessException {
            operations.multi();
            operations.opsForHash().putAll(signUpUserKey, signUpUserMap);
            return redisTemplate.exec();
        }
    });
}
 
Example #9
Source File: FebsLettuceRedisAutoConfigure.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Bean(name = "redisTemplate")
@ConditionalOnClass(RedisOperations.class)
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(factory);

    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(mapper);

    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    template.setKeySerializer(stringRedisSerializer);
    template.setHashKeySerializer(stringRedisSerializer);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();

    return template;
}
 
Example #10
Source File: RedisTemplateTransactionalTest.java    From mykit-delay with Apache License 2.0 6 votes vote down vote up
@Test
    public void test2() {
        System.out.println(11);
        List<Object> results = (List<Object>) redisTemplate.execute(new SessionCallback<List<Object>>() {
            @SuppressWarnings({"rawtypes", "unchecked"})
            public List<Object> execute(RedisOperations operations) {
                operations.multi();
                //new Jedis().multi();
                operations.opsForValue().set("abb", "233332");
                if (true) {
                    throw new eeee("xx");
                }
                operations.opsForValue().set("abb", "2");
//                operations.opsForValue().set("11", "22");
//                operations.opsForValue().get("11");
//                operations.opsForList().leftPush("aaa", 1);
//                operations.opsForList().range("aaa", 0l, 1l);
//                operations.opsForSet().add("bbbb", 12);
//                operations.opsForSet().members("bbbb");
                return operations.exec();
            }
        });
        for (Object o : results) {
            System.out.println(o);
        }
    }
 
Example #11
Source File: FollowServiceImpl.java    From MyCommunity with Apache License 2.0 6 votes vote down vote up
@Override
public void follow(int userId, int entityType, int entityId) {
    // 自己的关注者key
    String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
    // 被关注对象的粉丝key
    String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);

    redisTemplate.execute(new SessionCallback() {
        @Override
        public Object execute(RedisOperations redisOperations) throws DataAccessException {

            redisOperations.multi();
            // 自己的关注列表
            redisTemplate.opsForZSet().add(followeeKey, entityId, System.currentTimeMillis());
            // 被关注对象的粉丝列表
            redisTemplate.opsForZSet().add(followerKey, userId, System.currentTimeMillis());

            return redisOperations.exec();
        }
    });
}
 
Example #12
Source File: BusinessService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "illust_bookmarked", key = "#illustId+'1'+'30'")
    public void bookmarkOperation(int userId, String username, int illustId, int increment, int relationId) {
        //redis修改联系以及修改redis中该画作收藏数(事务)
//        Boolean isMember = stringRedisTemplate.opsForSet().isMember(RedisKeyConstant.BOOKMARK_REDIS_PRE + userId, String.valueOf(illustId));
//        if ((increment > 0 && isMember)
//                || (increment < 0 && !isMember)
//        ) {
//            throw new BusinessException(HttpStatus.BAD_REQUEST, "用户与画作的收藏关系请求错误");
//        }
        stringRedisTemplate.execute(new SessionCallback<>() {
            @Override
            public List<Object> execute(RedisOperations operations) throws DataAccessException {
                operations.multi();
                if (increment > 0) {
                    operations.opsForSet().add(RedisKeyConstant.BOOKMARK_REDIS_PRE + userId, String.valueOf(illustId));
                    //异步往mysql中写入
                    businessMapper.bookmark(userId, illustId, username, LocalDateTime.now());
                } else {
                    operations.opsForSet().remove(RedisKeyConstant.BOOKMARK_REDIS_PRE + userId, String.valueOf(illustId));
                    //异步往mysql中移除
                    businessMapper.cancelBookmark(userId, illustId);
                }
                operations.opsForHash().increment(RedisKeyConstant.BOOKMARK_COUNT_MAP_REDIS_PRE, String.valueOf(illustId), increment);
                return operations.exec();
            }
        });
    }
 
Example #13
Source File: UpdatableRedisCache.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public UpdatableRedisCache(
			String name,
			byte[] prefix,
			RedisOperations<? extends Object, ? extends Object> redisOperations,
			long expiration) {
		super(name, prefix, redisOperations, expiration);
		this.redisOperations = redisOperations;
//		self = PropertyAccessorFactory.forDirectFieldAccess(this);
		this.expirationInSeconds = expiration;
	}
 
Example #14
Source File: SessionConfig.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Bean
public RedisOperations<String, Object> sessionRedisOperations() {
	RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
	redisTemplate.setConnectionFactory(this.redisConnectionFactory);
	redisTemplate.setKeySerializer(new StringRedisSerializer());
	redisTemplate.setHashKeySerializer(new StringRedisSerializer());
	return redisTemplate;
}
 
Example #15
Source File: RedisSessionExpirationPolicy.java    From spring-session with Apache License 2.0 5 votes vote down vote up
RedisSessionExpirationPolicy(RedisOperations<Object, Object> sessionRedisOperations,
		Function<Long, String> lookupExpirationKey, Function<String, String> lookupSessionKey) {
	super();
	this.redis = sessionRedisOperations;
	this.lookupExpirationKey = lookupExpirationKey;
	this.lookupSessionKey = lookupSessionKey;
}
 
Example #16
Source File: RedisIndexedSessionRepository.java    From spring-session with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance. For an example, refer to the class level javadoc.
 * @param sessionRedisOperations the {@link RedisOperations} to use for managing the
 * sessions. Cannot be null.
 */
public RedisIndexedSessionRepository(RedisOperations<Object, Object> sessionRedisOperations) {
	Assert.notNull(sessionRedisOperations, "sessionRedisOperations cannot be null");
	this.sessionRedisOperations = sessionRedisOperations;
	this.expirationPolicy = new RedisSessionExpirationPolicy(sessionRedisOperations, this::getExpirationsKey,
			this::getSessionKey);
	configureSessionChannels();
}
 
Example #17
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 #18
Source File: RedisHttpSessionConfigurationTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void primaryConnectionFactoryRedisConfig() {
	registerAndRefresh(RedisConfig.class, PrimaryConnectionFactoryRedisConfig.class);

	RedisIndexedSessionRepository repository = this.context.getBean(RedisIndexedSessionRepository.class);
	RedisConnectionFactory redisConnectionFactory = this.context.getBean("primaryRedisConnectionFactory",
			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 #19
Source File: RedisHttpSessionConfigurationTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void qualifiedAndPrimaryConnectionFactoryRedisConfig() {
	registerAndRefresh(RedisConfig.class, QualifiedAndPrimaryConnectionFactoryRedisConfig.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 #20
Source File: RedisHttpSessionConfigurationTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void namedConnectionFactoryRedisConfig() {
	registerAndRefresh(RedisConfig.class, NamedConnectionFactoryRedisConfig.class);

	RedisIndexedSessionRepository repository = this.context.getBean(RedisIndexedSessionRepository.class);
	RedisConnectionFactory redisConnectionFactory = this.context.getBean("redisConnectionFactory",
			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 #21
Source File: RedisServiceImpl.java    From tom-crawler with Apache License 2.0 5 votes vote down vote up
@Override
public void addTaskToQueue(String queueKey, String url, String itemKey, String field, String value, Request request) {
    List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
        @Override
        public List<Object> execute(RedisOperations operations) throws DataAccessException {
            operations.multi();
            operations.opsForList().rightPush(queueKey, url);
            if (request != null && request.getExtras() != null) {
                operations.opsForHash().put(itemKey, field, value);
            }
            // This will contain the results of all ops in the transaction
            return operations.exec();
        }
    });
}
 
Example #22
Source File: RedisUtil.java    From Milkomeda with MIT License 5 votes vote down vote up
/**
 * 批量操作
 * @param runnable      业务体
 * @param redisTemplate RedisTemplate
 */
public static void batchOps(Runnable runnable, RedisTemplate<String, String> redisTemplate) {
    redisTemplate.executePipelined(new SessionCallback<Object>() {
        @Override
        public <K, V> Object execute(@NonNull RedisOperations<K, V> operations) throws DataAccessException {
            runnable.run();
            return null;
        }
    });
}
 
Example #23
Source File: RedisTemplateDriver.java    From redis-scheduler with MIT License 5 votes vote down vote up
@Override
public <T> T fetch(Function<Commands, T> block) {
    try {
        return redisTemplate.execute(new SessionCallback<T>() {
            @Override
            @SuppressWarnings("unchecked")
            public <K, V> T execute(RedisOperations<K, V> operations) throws DataAccessException {
                RedisConnectionCommands commands = new RedisConnectionCommands((RedisOperations<String, String>) operations);
                return block.apply(commands);
            }
        });
    } catch (RedisConnectionFailureException e) {
        throw new RedisConnectException(e);
    }
}
 
Example #24
Source File: RedisTemplateDriver.java    From redis-scheduler with MIT License 4 votes vote down vote up
private RedisConnectionCommands(RedisOperations<String, String> ops) {
    this.ops = ops;
}
 
Example #25
Source File: SessionConfig.java    From spring-session with Apache License 2.0 4 votes vote down vote up
@Bean
public RedisSessionRepository sessionRepository(RedisOperations<String, Object> sessionRedisOperations) {
	return new RedisSessionRepository(sessionRedisOperations);
}
 
Example #26
Source File: RedisConfig.java    From jee-universal-bms with Apache License 2.0 4 votes vote down vote up
@Bean
public RedisOperations<Object, Object> redisTemplate() throws UnknownHostException {
    RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
    template.setConnectionFactory(redisConnectionFactory());
    return template;
}
 
Example #27
Source File: DefaultBoundZSetOperations.java    From redis-admin with Apache License 2.0 4 votes vote down vote up
public RedisOperations<K, V> getOperations() {
	return ops.getOperations();
}
 
Example #28
Source File: DefaultBoundKeyOperations.java    From redis-admin with Apache License 2.0 4 votes vote down vote up
public DefaultBoundKeyOperations(K key, RedisOperations<K, ?> operations) {
	setKey(key);
	this.ops = operations;
}
 
Example #29
Source File: LikeServiceImpl.java    From MyCommunity with Apache License 2.0 4 votes vote down vote up
@Override
public void like(int userId, int entityType, int entityId, int entityUserId) {

    redisTemplate.execute(new SessionCallback() {
        @Override
        public Object execute(RedisOperations redisOperations) throws DataAccessException {

            String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
            String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
            // 当前用户是否点过赞
            Boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);

            // 开启事务
            redisOperations.multi();

            if (isMember) {
                redisTemplate.opsForSet().remove(entityLikeKey, userId);
                redisTemplate.opsForValue().increment(userLikeKey, -1);
            } else {
                redisTemplate.opsForSet().add(entityLikeKey, userId);
                redisTemplate.opsForValue().increment(userLikeKey, 1);
            }
            return redisOperations.exec();
        }
    });

}
 
Example #30
Source File: VerificationCacheConfiguration.java    From cola-cloud with MIT License 4 votes vote down vote up
@Bean
@ConditionalOnBean(RedisOperations.class)
public RedisVerificationCodeCache redisVerificationCodeCache(StringRedisTemplate stringRedisTemplate){
    return new RedisVerificationCodeCache(stringRedisTemplate);
}