/** * get MqttClient by clientKey * @param clientKey * @return * @throws MqttException */ public static MqttClient getMqttClient(String serverURI, String clientId,StringRedisTemplate redisTemplate) throws MqttException{ String clientKey=serverURI.concat(clientId); if(clientMap.get(clientKey)==null){ lock.lock(); if(clientMap.get(clientKey)==null){ MqttClientPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(serverURI, clientId, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); MqttCallback callback = new IMMqttCallBack(client,redisTemplate); client.setCallback(callback); connOpts.setCleanSession(true); client.connect(connOpts); clientMap.put(clientKey, client); } lock.unlock(); } return clientMap.get(clientKey); }
/** * RedisTemplate配置 * @param factory * @return */ @Bean @SuppressWarnings({"rawtypes", "unchecked"}) public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); //定义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.setValueSerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }
@Bean("redisTemplate") //新家的这个注解 10-26 12:06 @SuppressWarnings({ "rawtypes", "unchecked" }) public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisFactory){ StringRedisTemplate template = new StringRedisTemplate(redisFactory); 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; }
@Autowired public LoaderService(final RequestExecutorService requestExecutorService, final MonitorService monitorService, StringRedisTemplate template, @Value("${build.version}") String buildVersion, @Value("${build.timestamp}") String buildTimestamp) { this.requestExecutorService = requestExecutorService; this.monitorService = monitorService; this.template = template; this.buildVersion = buildVersion; this.buildTimestamp = buildTimestamp; this.myself = new Loader(); myself.setName(SystemInfo.hostname()); myself.setStatus(Status.IDLE); myself.setVersion(buildVersion + " (" + buildTimestamp + ")"); }
public static void main(String[] args) throws InterruptedException { ApplicationContext context = SpringApplication.run(RedisAndLockApplication.class, args); StringRedisTemplate stringRedisTemplate = context.getBean(StringRedisTemplate.class); RedisLock lock = new RedisLock(stringRedisTemplate, "test_002"); // Lock lock = new ReentrantLock(); final Printer outer = new Printer(lock); Thread t1 = new Thread(() -> outer.output("One : I am first String !!")); Thread t2 = new Thread(() -> outer.output("Two : I am second String !!")); Thread t3 = new Thread(() -> outer.output("Three : I am third String !!")); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); System.exit(0); }
public RedisMessageChannelBinder(RedisConnectionFactory connectionFactory, String... headersToMap) { Assert.notNull(connectionFactory, "connectionFactory must not be null"); this.connectionFactory = connectionFactory; StringRedisTemplate template = new StringRedisTemplate(connectionFactory); template.afterPropertiesSet(); this.redisOperations = template; if (headersToMap != null && headersToMap.length > 0) { String[] combinedHeadersToMap = Arrays.copyOfRange(BinderHeaders.STANDARD_HEADERS, 0, BinderHeaders.STANDARD_HEADERS.length + headersToMap.length); System.arraycopy(headersToMap, 0, combinedHeadersToMap, BinderHeaders.STANDARD_HEADERS.length, headersToMap.length); this.headersToMap = combinedHeadersToMap; } else { this.headersToMap = BinderHeaders.STANDARD_HEADERS; } this.errorAdapter = new RedisQueueOutboundChannelAdapter( parser.parseExpression("headers['" + ERROR_HEADER + "']"), connectionFactory); }
public RedisTestBinder(RedisConnectionFactory connectionFactory) { RedisMessageChannelBinder binder = new RedisMessageChannelBinder(connectionFactory); GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerSingleton(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME, new DefaultMessageBuilderFactory()); DefaultHeaderChannelRegistry channelRegistry = new DefaultHeaderChannelRegistry(); channelRegistry.setReaperDelay(Long.MAX_VALUE); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.afterPropertiesSet(); channelRegistry.setTaskScheduler(taskScheduler); context.getBeanFactory().registerSingleton( IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME, channelRegistry); context.refresh(); binder.setApplicationContext(context); binder.setCodec(new PojoCodec()); setBinder(binder); template = new StringRedisTemplate(connectionFactory); }
@Test public void testWithKey() throws Exception{ //Setup String key = "foo"; StringRedisTemplate redisTemplate = createStringRedisTemplate(redisConnectionFactory); redisTemplate.delete(key); RedisList<String> redisList = new DefaultRedisList<String>(key, redisTemplate); List<String> list = new ArrayList<String>(); list.add("Manny"); list.add("Moe"); list.add("Jack"); //Execute Message<List<String>> message = new GenericMessage<List<String>>(list); sink.input().send(message); //Assert assertEquals(3, redisList.size()); assertEquals("Manny", redisList.get(0)); assertEquals("Moe", redisList.get(1)); assertEquals("Jack", redisList.get(2)); //Cleanup redisTemplate.delete(key); }
@Autowired public DefaultPersistenceService(@Qualifier("orderingTemplate") @NonNull final StringRedisTemplate orderingTemplate, @Qualifier("valueTemplate") @NonNull final RedisTemplate<String, EmailSchedulingData> valueTemplate) { this.orderingTemplate = orderingTemplate; this.orderingTemplate.setEnableTransactionSupport(true); this.valueTemplate = valueTemplate; RedisSerializer<String> stringSerializer = new StringRedisSerializer(); JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer(); this.valueTemplate.setKeySerializer(stringSerializer); this.valueTemplate.setValueSerializer(jdkSerializationRedisSerializer); this.valueTemplate.setHashKeySerializer(stringSerializer); this.valueTemplate.setHashValueSerializer(stringSerializer); this.valueTemplate.setEnableTransactionSupport(true); this.valueTemplate.afterPropertiesSet(); }
public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); // invoke the CONFIG /* * application context then starts the message listener container, and * the message listener container bean starts listening for messages */ ctx.register(RedisConfig.class); ctx.refresh(); /* * retrieves the StringRedisTemplate bean from the application context * and uses it to send a "Hello from Redis!" message on the "chat" topic */ StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class); CountDownLatch latch = ctx.getBean(CountDownLatch.class); LOGGER.info("* Sending message..."); template.convertAndSend("chat", "Hello from Redis!"); latch.await(); System.exit(0); }
@Bean public RedisTemplate getStringRedisTemplate() { StringRedisTemplate clusterTemplate = new StringRedisTemplate(); clusterTemplate.setConnectionFactory(jedisConnectionFactory()); clusterTemplate.setKeySerializer(new StringRedisSerializer()); clusterTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return clusterTemplate; }
@SuppressWarnings({"unchecked","rawtypes"}) @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; }
@Override public void post(String username, String message) { JedisPool jedisPool = JedisFactory.getPool(); try (Jedis jedis = jedisPool.getResource()) { long tweetId = jedis.incr("id"); String key = username + ":tweet:" + tweetId; System.out.println("key der nachricht:" + key); jedis.hset(key, "message", message); Calendar cal = Calendar.getInstance(); java.util.Date time = cal.getTime(); DateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); jedis.hset(key, "date", formatter.format(time)); jedis.lpush("global", key); jedis.lpush(username + ":personal", key); Set<String> werEinemFolgt = jedis.smembers(username + ":follower"); for (Iterator<String> iterator = werEinemFolgt.iterator(); iterator.hasNext();) { String iter = iterator.next(); System.out.println("Iterator: " + iter); jedis.lpush(iter + ":follower:tweet", key); System.out.println("name von dem Typen auf wesen liste man schreibt: " + iter); } ApplicationContext ctx = TrumpetWebApplication.getCtx(); StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class); CountDownLatch latch = ctx.getBean(CountDownLatch.class); template.convertAndSend("chat", "Neue Nachricht von: " + username); } catch (Exception e) { System.out.println("Mock catch block post"); e.printStackTrace(); } }
@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; }
public TokenAuthenticationServiceImpl(UserRepository userRepository, StringRedisTemplate stringRedisTemplate) { this.userRepository = userRepository; this.stringRedisTemplate = stringRedisTemplate; // TODO: parse this as a property tokenHandler = new TokenHandler(DatatypeConverter.parseBase64Binary("9SyECk96oDsTmXfogIfgdjhdsgvagHJLKNLvfdsfR8cbXTvoPjX+Pq/T/b1PqpHX0lYm0oCBjXWICA==")); }
@Autowired public KyDbPresenter(DbRoutinePresenter dbRoutinePresenter, DbEmployeePresenter dbEmployeePresenter , DeviceGroupRepository deviceGroupRepository, DbDevicePresenter dbDevicePresenter , DbSettingPresenter dbSettingPresenter, StringRedisTemplate stringRedisTemplate) { this.dbRoutinePresenter = dbRoutinePresenter; this.deviceGroupRepository = deviceGroupRepository; this.dbSettingPresenter = dbSettingPresenter; this.dbDevicePresenter = dbDevicePresenter; this.dbEmployeePresenter = dbEmployeePresenter; this.stringRedisTemplate = stringRedisTemplate; }
@Autowired public SipMessageStatisticHandler(@Value("${statistic.partition}") String partition, @Value("${ttl.statistic}") String ttl, @Value("${statistic.host:#{null}}") String hosts, @Value("${statistic.inclusions:#{null}}") String inclusions, @Value("${statistic.exclusions:#{null}}") String exclusions, StringRedisTemplate redis) { this.partition = PartitionFactory.ofPattern(partition); this.ttl = PartitionFactory.ofPattern(ttl).duration(); this.hosts = split(hosts); this.inclusions = split(inclusions); this.exclusions = split(exclusions); this.redis = redis; }
public void persistImageCaptcha(String sid,String capText){ StringRedisTemplate template= redisConfig.getTemplate(); String format = imageCaptchaFormat(sid); ValueOperations<String,String> obj = template.opsForValue(); obj.set(format,capText.toLowerCase()); template.expire(format , getImageTimeOut(), TimeUnit.MINUTES); }
public void persistPhoneCaptcha(String phone , String code){ StringRedisTemplate template = getTemplate(); String format = phoneCaptchaFormat(phone); ValueOperations<String,String> obj = getTemplate().opsForValue(); obj.set(format,code.toLowerCase()); template.expire(format ,getPhoneTimeOut(), TimeUnit.MINUTES); }
@Bean("redisTemplate") public RedisTemplate<?, ?> getRedisTemplate(){ RedisTemplate<?,?> template = new StringRedisTemplate(jedisConnectionFactory); GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); template.setKeySerializer(stringRedisSerializer); template.setValueSerializer(genericJackson2JsonRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template.setHashValueSerializer(genericJackson2JsonRedisSerializer); return template; }
@Bean @SuppressWarnings({ "rawtypes", "unchecked" }) 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; }
@Override public void afterPropertiesSet() throws Exception { templates = new ArrayList<RedisTemplate>(); List<JedisConnectionFactory> factorys = connectionFactory.getFactories(); for (JedisConnectionFactory factory : factorys) { StringRedisTemplate template = new StringRedisTemplate(factory); template.setKeySerializer(keySerializer); template.setValueSerializer(valueSerializer); template.setHashKeySerializer(hashKeySerializer); template.setHashValueSerializer(hashValueSerializer); // 执行必要方法 template.afterPropertiesSet(); templates.add(template); } }
@Before public void setUp() throws Exception { RedisConnectionFactory connectionFactory = TestRedis.connectionFactory(); dao.setConnectionFactory(connectionFactory); dao.setNamespace("namespace"); dao.afterPropertiesSet(); redis = new StringRedisTemplate(); redis.setConnectionFactory(connectionFactory); redis.afterPropertiesSet(); }
@Autowired public RedisConfigPropertySourceProvider(StringRedisTemplate stringRedisTemplate, RedisConfigKeysProvider redisConfigKeysProvider, RedisPropertyNamePatternProvider redisPropertyNamePatternProvider, ConfigServerProperties configServerProperties) { this.stringRedisTemplate = stringRedisTemplate; this.redisConfigKeysProvider = redisConfigKeysProvider; this.redisPropertyNamePatternProvider = redisPropertyNamePatternProvider; this.configServerProperties = configServerProperties; }
@Bean public RedisTemplate<String, String> redisTemplate( RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); setSerializer(template); // 设置序列化工具,这样ReportBean不需要实现Serializable接口 template.afterPropertiesSet(); return template; }
private void setSerializer(StringRedisTemplate template) { 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); }
@Test public void testDefaultPayloadSerializer() throws Exception { StringRedisTemplate template = new StringRedisTemplate(connectionFactory); template.afterPropertiesSet(); adapter.afterPropertiesSet(); adapter.handleMessage(new GenericMessage<String>("message1")); assertEquals("message1", template.boundListOps(QUEUE_NAME).rightPop()); }
@Bean @Primary public StringRedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(connectionFactory); template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; }
@After public void clear() { assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()).opsForZSet() .size("keys." + this.prefix)).isGreaterThan(0); this.repository.reset("foo"); this.repository.reset("bar"); assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) .opsForValue().get(this.prefix + ".foo")).isNull(); assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) .opsForValue().get(this.prefix + ".bar")).isNull(); }
@After public void clear() { assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) .opsForValue().get(this.prefix + ".foo")).isNotNull(); this.repository.reset("foo"); this.repository.reset("bar"); assertThat(new StringRedisTemplate(this.redis.getConnectionFactory()) .opsForValue().get(this.prefix + ".foo")).isNull(); }
@Bean @ConditionalOnMissingBean(StringRedisTemplate.class) public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; }
@Test public void testDefaultRedisConfiguration() throws Exception { load(); assertThat(this.context.getBean("redisTemplate", RedisOperations.class)) .isNotNull(); assertThat(this.context.getBean(StringRedisTemplate.class)).isNotNull(); }
@Autowired public MultiRedisApplication(@Qualifier("userStringRedisTemplate") StringRedisTemplate userStringRedisTemplate, @Qualifier("roleStringRedisTemplate") StringRedisTemplate roleStringRedisTemplate, UserService userService) { this.userStringRedisTemplate = userStringRedisTemplate; this.roleStringRedisTemplate = roleStringRedisTemplate; this.userService = userService; }
@Bean(name = "userRedisTemplate") public RedisTemplate userRedisTemplate(@Qualifier("userRedisConnectionFactory") RedisConnectionFactory cf) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(cf); setSerializer(stringRedisTemplate); return stringRedisTemplate; }
@Bean(name = "roleRedisTemplate") public RedisTemplate roleRedisTemplate(@Qualifier("roleRedisConnectionFactory") RedisConnectionFactory cf) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(cf); setSerializer(stringRedisTemplate); return stringRedisTemplate; }