Quantcast
Channel: Active questions tagged redis+java - Stack Overflow
Viewing all 2203 articles
Browse latest View live

Redisson JAR execution: ClassNotFoundException: org.redisson.RedissonReference

$
0
0

Spring Boot v2.1.2 on Java 11 not working when being executed via compiled Jar file complaining on missing class (ClassNotFoundException: org.redisson.RedissonReference). Although everything works when running code directly via Intellij.

See below maven pom.xml and stacktrace that I get when running compiled jar:

'13-02-2020 21:14:56.905 [redisson-netty-2-18] WARN  i.n.channel.DefaultChannelPipeline.onUnhandledInboundException - An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
...skipping...
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
        at io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
        at io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
        at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1432)
        at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1199)
        at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1243)
        at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:502)
        at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:441)
        at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:278)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1434)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:965)
        at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:648)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:583)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:500)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:462)
        at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:897)
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
        at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.io.IOException: java.lang.RuntimeException: class not found CLASSNAME:org.redisson.RedissonReference loader:jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f
        at org.nustaq.serialization.FSTObjectInput.readObject(FSTObjectInput.java:247)
        at org.redisson.codec.FstCodec$1.decode(FstCodec.java:250)
        at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:368)
        at org.redisson.client.handler.CommandDecoder.decodeCommand(CommandDecoder.java:196)
        at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:134)
        at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:104)
        at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:502)
        at io.netty.handler.codec.ReplayingDecoder.callDecode(ReplayingDecoder.java:366)
        ... 41 common frames omitted
Caused by: java.lang.RuntimeException: class not found CLASSNAME:org.redisson.RedissonReference loader:jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f
        at org.nustaq.serialization.FSTClazzNameRegistry.classForName(FSTClazzNameRegistry.java:235)
        at org.nustaq.serialization.FSTClazzNameRegistry.classForName(FSTClazzNameRegistry.java:190)
        at org.nustaq.serialization.FSTClazzNameRegistry.decodeClass(FSTClazzNameRegistry.java:173)
        at org.nustaq.serialization.coders.FSTStreamDecoder.readClass(FSTStreamDecoder.java:478)
        at org.nustaq.serialization.FSTObjectInput.readClass(FSTObjectInput.java:939)
        at org.nustaq.serialization.FSTObjectInput.readObjectWithHeader(FSTObjectInput.java:347)
        at org.nustaq.serialization.FSTObjectInput.readObjectInternal(FSTObjectInput.java:331)
        at org.nustaq.serialization.FSTObjectInput.readObject(FSTObjectInput.java:311)
        at org.nustaq.serialization.FSTObjectInput.readObject(FSTObjectInput.java:245)
        ... 48 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.redisson.RedissonReference
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:398)
        at org.nustaq.serialization.FSTClazzNameRegistry.classForName(FSTClazzNameRegistry.java:197)
        ... 56 common frames omitted

Maven pom.xml

...
    <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <configuration>
                        <includeSystemScope>true</includeSystemScope>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>3.0.1</version>
                    <executions>
                        <execution>
                            <id>attach-sources</id>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                    <configuration>
                        <release>11</release>
                    </configuration>
                </plugin>
            </plugins>
        </build>
...

Will be happy to receive directions on what is wrong.


Jedis does not delete keys

$
0
0

I have just installed redis' last version on Ubuntu 18.04.3. I have tried out writing values directly with redis-cli.

127.0.0.1:6379> set myket somevalue

I am now trying to delete all values from Jedis:

    Jedis jedis = new Jedis("localhost", 6379);
    Set<String> names=jedis.keys("NAME:*");
    System.out.println("There are " + names.size() +  " keys to delete");
    Iterator<String> it = names.iterator();
    while (it.hasNext()) {
        String s = it.next();
        jedis.del(s);
        System.out.println(s + " has been deleted");
    }

However, it always says that there are 0 keys right now. When I query it from redis-clidirectly, it is still there. How can I delete the keys from Jedis?

initialize a default key value pair while returning RedisTemplate object in java

$
0
0

I am trying to set the default key value pair while returning the redisTemplate from below chunk of code. Please help me if it is possible.

public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    redisTemplate.setExposeConnection(true);
    redisTemplate.setKeySerializer(new StringRedisSerializer());

    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    return redisTemplate;
}

It should be look something like that: enter image description here

Spring RedisTemplate : Serialise multiple Model classes into JSON.Need to use Multiple RedisTemplates?

$
0
0

I am using Spring Redis support to save my objects in Redis.

I have several DAOs which handle different Model classes:

For example, ShopperHistoryDao save/retrieve objects of ShopperHistoryModel, ShopperItemHistoryDao save/retrieve objects of ItemHistoryModel.

I want to use JacksonJsonRedisSerializer to serialise/deserialize my objects to/from json.

But in the constructor of JacksonJsonRedisSerializer, it takes one specific Model class.

JacksonJsonRedisSerializer(Class<T> type)

Does that mean, I have to configure separate RedisTemplates for each different Model class and use them in appropriate DAO implementation?

Something like:

<bean id="redisTemplateForShopperHistoryModel" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="jedisConnectionFactory" />
    <property name="valueSerializer">
        <bean id="redisJsonSerializer" 
                        class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">
            <constructor-arg type="java.lang.Class" value="ShopperHistoryModel.class"/>
        </bean>   
    </property>
</bean>


<bean id="redisTemplateForItemHistoryModel" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="jedisConnectionFactory" />
    <property name="valueSerializer">
        <bean id="redisJsonSerializer" 
                        class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">
            <constructor-arg type="java.lang.Class" value="ItemHistoryModel.class"/>
        </bean>   
    </property>
</bean>

Spring Data Redis search in collection

$
0
0

Let's imagine I've got entity like

@RedisHash(value = "Question",timeToLive = -1)
@Data
public class Question {

private String id;
@Indexed private String question;
@Indexed private String indexName;
@Indexed  List<Long> folderIds;
List<Answer> answers;

The scenarios to get this entity from redis will be the following 1. Search by question, indexName and exact match of folderIds list. 2. Search by indexName and specific folderId in this folderIds list.

As I understand - Spring Data Redis doesn't support IN, CONTAINS and all other stuff to search in collection. So my first idea was to store folderIds as string (in presorted order and joined with comma separator). This will help in first scenario. But for second scenario it won't work, cause LIKE operation is also not supported in Repository. And only way i see here - grab everything by indexName and then filter this large collection manually, but it looks like not very performance friendly.

Maybe I'm missing something and there is some good way to deal with such case. Thanks!

Spring Cacheable unless condition doesn't work

$
0
0

I have developed a REST end-point in Springboot that takes a String ID and responds with a ModelAndView. This end-point is marked with @Cacheable annotation. Now there are two things that can happen at the given end-point.

Case 1: The request ID exists in the DB and yields a URL to which redirection needs to happen. In this case, response should be cached so that upon consecutive requests of the same ID, the result can be served from Cache

Case 2: The requested ID doesn't exist in the DB and thus redirection should happen to a specific URL and no caching should be done in this scenario.

So below is my method

@GetMapping("{id}")
    @Cacheable(value = "url-single", key = "#id", unless = "#result.view!=\"redirect:/notfound\"")
    public ModelAndView redirect(@PathVariable("id") String id, ServletRequest servletRequest,
            ServletResponse servletResponse) {
        HttpServletRequest request = HttpServletRequest.class.cast(servletRequest);
        LOG.info("Redirection request from: {} for Short URL Key: {}", request.getRemoteAddr(), id);
        try {
            Optional<String> originalUrlOptional = urlManagerService.retrieveOriginalUrl(id);
            if (originalUrlOptional.isPresent() && !StringUtils.isEmpty(originalUrlOptional.get())) {
                LOG.info("Found Original URL: {} for Short URL Key: {}", originalUrlOptional.get(), id);
                return new ModelAndView("redirect:https://" + originalUrlOptional.get());
            }

        } catch (NoSuchElementException e) {
            LOG.error("Error while redirecting: {}", e.getMessage(), e);
        }
        return new ModelAndView("redirect:/notfound");
    }

If I understand it correctly from here, the keyword unless in @Cacheable applies to the return type and in order to access any particular member variable of the return type object, we have to refer to it as #result.attributeName <comparison> <value>.

So why isn't anything being stored in my Redis cache? If I remove the unless condition, everything gets stored. Is the condition not correct?

Spring Redis Null Pointer Exception on redisTemplate

$
0
0

Hi I am working with java-redis integration with jedis and I came up with this problem when trying to setup project. I am new to spring so there might be some issues with initial setup. This is the code that I am trying to work with:

RedisConfig.java

@Configuration
public class RedisConfig {

  @Bean
  public RedisConnectionFactory jedisConnectionFactory() {
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxTotal(1000);

    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
    jedisConnectionFactory.setHostName(Properties.getInstance().getPropertyValueReader().getAWSRedisEndPoint());
    jedisConnectionFactory.setPort(6379);
    return jedisConnectionFactory;
  }

  @Bean
  public <K, V> RedisTemplate<String, V> getRedisTemplate() {
    JdkSerializationRedisSerializer jackson2JsonRedisSerializer = new JdkSerializationRedisSerializer();
    RedisTemplate<String, V> redisTemplate = new RedisTemplate<String, V>();
    redisTemplate.setConnectionFactory(jedisConnectionFactory());
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
    redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    return redisTemplate;
  }

}

CacheRepository.java

public interface CacheRepository<T, V> {
    V get(Object key);

    void add(Object redisKey, Object key, T value);

    void add(T key, V value);

    void expire(Object key);
}

CacheRepositoryImpl.java

@Component
public class CacheRepositoryImpl<T, V> implements CacheRepository<T, V> {

    @Autowired
    protected RedisTemplate<String, V> redisTemplate;

    @Override
    public V get(Object key) {
    }

    @Override
    public void expire(Object key) {
    }

    @Override
    public void add(Object redisKey, Object key, T value) {
    }

    @Override
    public void add(T key, V value) {
    }
}

VendorInformationCacheRepository.java

public class VendorInformationCacheRepository extends CacheRepositoryImpl<String, HashMap<String, List<Vehicles>>> {

private static final String KEY = "Vendors";

@Override
public void add(String key, HashMap<String, List<Vehicles>> value){
    System.out.println(redisTemplate);                 // this prints null
    redisTemplate.opsForHash().put(KEY, key, value);
}

}

BaseController.java

VendorInformationCacheRepository vicr = new VendorInformationCacheRepository();
vicr.add("testKey",  myNewList);

In VendorInformationCacheRepository.javaredisTemplate.opsForHash().put(KEY, key, value); gives null pointer exception. This is the stack trace of the error:

java.lang.NullPointerException

at com.moveinsync.cache.CacheRepositoryImpl.add(CacheRepositoryImpl.java:35)
at com.moveinsync.controllers.BaseController.redisTest(BaseController.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Any help would be highly appreciated. Thanks in advance. Cheers

RedisSystemException Nested exception is An existing connection was forcibly closed by the remote host from #SpringBoot Application

$
0
0

org.springframework.data.redis.RedisSystemException: Redis exception; nested exception is io.lettuce.core.RedisException: java.io.IOException: An existing connection was forcibly closed by the remote hostenter image description here


How to implement Competition leaderboard using redis sorted set

$
0
0

I'm using Redis sorted set to maintain the leaderboard of my game. I have a scenario where I need to maintain the same rank of the users who have the same score as the Competition leaderboard. Eg.

| member | score | rank |
— — — — — — — — — — —
| member_1 | 50 | 1 |
| member_2 | 50 | 1 |
| member_3 | 30 | 3 |
| member_4 | 30 | 3 |
| member_5 | 10 | 5 |

As of now, I'm using default implementation of Redis sorted set which returns the ranking lexicographically.

127.0.0.1:6379> zadd test-leaderboard 9 user1
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 5 user2
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 5 user3
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 3 user4
(integer) 1

If I query for user2 and user3 rank, I get a different result

127.0.0.1:6379> zrank test-leaderboard user2
(integer) 1
127.0.0.1:6379> zrank test-leaderboard user3
(integer) 2

I checked Redis documentation, there is no such feature to do so. So I want to know what I have to do or what is the best way to implement this functionality.

Note: I have 10K records in SET and I need to maintain it at runtime and I'm using Java programming language.

Adding rule to windows firewall in java for redis server which takes command line arguments like config file and port no

$
0
0

I am trying to avoid the Windows Security Alert dialog box by adding a rule in the firewall. I am using java program which launches the redis server along with a config file and port no. In order to add a rule to firewall i intend to use netsh advfirewall command, but the problem is that how do i pass the config file to it and the port no.

command to start redis :
redis-server <conf> --port <port>

What i am doing in java:

                List<String> commands = new ArrayList<>();
                commands.add("netsh");
                commands.add("advfirewall");
                commands.add("firewall");
                commands.add("add");
                commands.add("rule");
                commands.add(String.format("name=RULE FOR REDIS-SERVER: %s", redisExeFilePath));
                commands.add("dir=in");
                commands.add("action=allow");
                commands.add(String.format("program=%s", redisExeFilePath));
                commands.add(configFilePath);
                commands.add("--port" + "" + serverPort.toString());

                ProcessBuilder pb = new ProcessBuilder(commands);
                Process process = pb.start();

However this does not bring up the redis server nor does it add a exception to windows firewall.

What am i doing wrong here ?

Lua script coverts empty array to object

$
0
0

Lua script converts empty array as an object. How to avoid conversion.

test.lua

local json_str = '{\"items\":[],\"properties\":{}}'
return cjson.encode(cjson.decode(json_str))

Output

redis-cli --eval test.lua

"{\"items\":{},\"properties\":{}}"

items are an array [] but the output is an object {}

How to use Redis and Jedis with Bungeecord and Bukkit to communicate across servers

$
0
0

This links to a previous question I had before finding Jedis/Redis. I am on a Windows 10 PC and although I have found documents explaining how to code with Jedis (and have got the library working) I do not know how to use Redis/Jedis which has to be installed (I think). The download page downloads a compressed folder which I don't know how to install from (I have uncompressed it and there's no exe to be found). I apologise in advance for the time wasted and my probable ignorance in this subject.

If you need any more detail feel free to leave a comment or answer and if you know anything about this that would be a huge help. Even a link to some working examples or tutorials would be amazing.

Thanks for reading this far and for your help,

Edward

Timeout for JedisConnectionFactory

$
0
0

Is there a way to configure Read timeout in JedisConnFactory as we have for HttpRequestFactory? I've configured JedisConnFactory with timeout property as below. Does it include both Connection timeout and Read timeout?

final JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(redisHost);      
redisConnectionFactory.setTimeout(10000);
redisConnectionFactory.setPort(port);
redisConnectionFactory.setUsePool(true);
redisConnectionFactory.afterPropertiesSet();

@Bean(name = "redisCacheManager")
    public CacheManager cacheManager(final RedisTemplate<String,Object> redisTemplate) {
        final RedisCacheManager manager = new RedisCacheManager(redisTemplate());
        manager.setDefaultExpiration(Long.parseLong(expiryInSecs));
        return manager;
    }

    @Bean(name="redisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        redisTemplate.setKeySerializer(stringRedisSerializer());
        redisTemplate.setHashKeySerializer(stringRedisSerializer());
        redisTemplate.setValueSerializer(stringRedisSerializer());
        redisTemplate.setHashValueSerializer(stringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

How to use Redis command "bitcount" in java

$
0
0

I am trying to use redis bitmap to save online user, use command "bitcount onlineUser" to count the number of online user.I use RedisTemplate to deal with redis. But I can't find any API in RedisTemplate to execute command "bitcount'.How can I execute command "bitcount" in java? Any help will be appreciated.

 @Override
    public Boolean saveOnlineUser(Long userId) {
        ValueOperations<String,Object> ops = redisTemplate.opsForValue();
        return ops.setBit("onlineUser",userId,true);
    }

    @Override
    public Integer getOnlineUser() {
        //I want to use Redis command "bitcount 'onlineUser'" here to count the number of online users
        return redisTemplate.opsForValue().;
    }

How to sync an operation between Redis and MongoDB

$
0
0

I'll try to keep my question short and simple.

Say, I have a Springboot application that allows creation of a certain entity with Time to live. I store the entity in a MongoDB. When a request comes to get the entity, the application fetches it from DB, caches it in Redis and sends the response. Next consecutive requests will be served from the cache

When the TTL (which is configurable and is determined at the time of creation of the entity) of the entity expires, it's going to be removed from the MongoDB.

I am having trouble figuring out how to sync that with the Redis cache. I was thinking that at the time of the first query when I am caching the response, I would cache it with the remaining TTL of the entity, so that I don't have to do anything extra to remove it from both Mongo and Redis. Both Redis and Mongo will take care of the removal on their own. Currently, I cache responses using the @Cacheable annotaion, but I couldn't find out any extra parameter in that annotation that will dynamically set a TTL.

Is there a way to achieve it keeping the @Cacheable annotation on my method?


does hibernate-redis supports 2nd level cache shared by different hibernate instances

$
0
0

We want to use the hibernate-redis project https://github.com/debop/hibernate-redis to support redis 2nd level cache.

Is this cache actually shared by different hibernate instances on different machines ? It should be so as redis is intended to be used that way, I have not confirmed that, but is anyone around there who used the redis cache to that effect.

For example, hibernate query from machine 2 does not hit the database and fetches the result from redis instead, because a previous query on machine 1 already fetched the same data and the data is stored in the redis cache.

Does Redisson Hibernate Cache Module share same data in multiple containers?

$
0
0

We want to use the redisson-hibernate project https://github.com/redisson/redisson/tree/master/redisson-hibernate to support redis 2nd level cache.

I tested redisson-hibernate module in multiple containers by using same Redis database. But it doesn't share same data. Java application in the first container doesn't see updates of the records made by Java application in the second container. Every Java application have own version of the records.

Does Redisson Hibernate Cache Module can share same data in multiple containers?

org.springframework.data.mapping.MappingException, can not convert map to object using hashmapper

$
0
0

when converting map read from redis to my entity object,it throws such an exception: org.springframework.data.mapping.MappingException: Unexpected token (VALUE_STRING), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class java.util.List at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: edu.why.core.model.IDInfo["fixParts"])
here is my code:

@org.junit.jupiter.api.Test
    public void test8() {
        IDInfo info=new IDInfo();
        info.setIndexPosition(1);
        info.setLength(4);
        info.setNextIndex(2);
        info.setStartIndex(100);
        info.setStep(1);
        List<FixedPart> list=new ArrayList<>();
        list.add(new StringFixedPart("ss"));
        list.add(new DateTimeFixedPart("y"));
        info.setFixParts(list);
        redisTemplate.opsForHash().putAll("map",mapper.toHash(info));
        Map map=redisTemplate.opsForHash().entries("map");
        IDInfo result=(IDInfo) mapper.fromHash(map);//this line throws the exception
    }

this is my mapper:

    @Bean
    public HashMapper hashMapper(){
        return new DecoratingStringHashMapper(new Jackson2HashMapper(false));
    }

this is my entity:

public class IDInfo {
    private long startIndex;      //the first index
    private int indexPosition;   //the position of the index
    private int length;             //the length of the index
    private long nextIndex;       //the next index to be returned
    private int step;               //the amount each increase by
    private List<FixedPart> fixParts; //the content of fixpart
    //omit setter and getter 
}

It work well when converting object to Map,but throw an exception when converting Map back to Objcet.Why?

Java 8 Lambda expression with Serialization

$
0
0

In our Web application project, we are using the Redis to manage the session. To support it, we are serializing any object which will be stored in the session.

For example, we use DTO's to hold the bean data which is used to display on the screen. Even if the DTO having any other object inside (Composition) we also have to serialize it otherwise, we get NotSerializableException.

I had a problem when I was creating an anonymous inner class to implement the Comparator like below:

Collections.sort(people, new Comparator<Person>() {
    public int compare(Person p1, Person p2) {
        return p1.getLastName().compareTo(p2.getLastName());
    }
});

The above code threw the NotSerializableException and I resolved it by creating a class that implements the Comparator as well as Serializable interface. The problem was, it was thrown inside the JSP page which was using this DTO. I had to do a lot of debugging to find the actual problem.

But now, I'm wondering to change the above code to use Lambda expression like below:

Collections.sort(people, (p1, p2) -> p1.getLastName().compareTo(p2.getLastName()));

However, I fear the same exception might occur. Does the Lambda expression create objects internally?

Is it possible to store session in two different stores using Spring Session and Spring Boot?

$
0
0

I am using redis for storing session in my Spring Boot app. I am also using Spring Session library to achieve this. I have two different redis instances namely US redis and EU redis. Once someone enters my app(after logging in of course), I want to store their sessions in both US redis and EU redis servers. Mind you that these both redis instances are masters and are not in any master-slave setup. This is what I have so far in my spring setup.

@EnableRedisHttpSession
@Configuration
public class RedisConfig{

}

Note: removed other security code for brevity.

According to @EnableRedisHttpSession docs, we need to add one RedisConnectionFactory instance, however Spring Boot by default does this.

So right now, once the user logs in, their session is stored in US redis(I added US redis related information in application.yml).

However whenever a session is stored in US redis, I want to replicate the same in EU redis server. How can I achieve this? Do I need to create another RedisConnectionFactory bean and manually save it? If manually save it, how to do so?

Note: This use case might not be following the best design practices(that is we are storing user session in multiple places). However I do understand this, but I do have a use case for this.

Viewing all 2203 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>