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

Should it call method hasKey before get when use redis or other DB

$
0
0

When I want to get data form Redis, I was confused about that whether or not call method redis.hasKey before redis.get.

Someone write like this:

if (redis.hasKey('xxx')) {    return redis.get('xxx');}return ...

and the others write like this:

Object value = redis.get('xxx')if (value != null) {    return value}return ...

I think the second one was good, because it just once Redis operation, the first one has two. Which did you choose and why? Thanks.

Sorry for my poor English.


Redis Connection Issue with jedis

$
0
0

I am using this code but getting connection issue:

JedisConnectionFactory jedisConnectionFactory() {    JedisConnectionFactory jedisConnectionFactory = null;    try {        RedisStandaloneConfiguration redisStandAloneConfiguration = new RedisStandaloneConfiguration(hostName,            port);        // make jedis connection factory thread safe (for multi-threaded        // environment)        JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling().build();        jedisConnectionFactory = new JedisConnectionFactory(redisStandAloneConfiguration, jedisClientConfiguration);        // jedisConnectionFactory uses connection pool by default but with        // max total of 8        jedisConnectionFactory.getPoolConfig().setMaxTotal(50);        jedisConnectionFactory.getPoolConfig().setMaxIdle(50);        jedisConnectionFactory.afterPropertiesSet();    } catch (RedisConnectionFailureException e) {        LOGGER.error("RedisConnectionFailureException in RedisConnector class, Connection break with JEDIS "+            e.getMessage());    }    return jedisConnectionFactory;}

How to stop vertx threads?

$
0
0

So here's the situation: I'm implementing the caching of our webapp using vertx-redis (we were formerly using lettuce). Pretty simple mechanism, there is an anotation we use on endpoints which is responsible to invoke the redis-client (whatever implementation we are using) and, if there is cached info for the given key it should be used as response body and the request should be finished with no processing.

But there's this really annoying behavior with the vertx-redis implementation in witch ending the request don't stop the processing. I make the request, get the quick response since there was cached info, but I can still see in the logs that the app keeps the processing going on, as if the request was still open. I believe that it's because I'm ending the response inside the handler for the redis client call, like this:

client.get("key", onResponse -> {    if (onResponse.succeeded() && onResponse.result() != null) {        //ending request from here    }});

I realize that I could maybe reproduce the behavior as it was before if I could do something like this:

String cachedInfo = client.get("key").map(onResponse -> onResponse.result());// endResponse

But as we know, vertx-redis is a semantic API and every method returns the same instance of RedisClient. I also thought about doing something like this:

private String cachedInfo; ...client.get("key", onResult -> {    if (onResponse.succeeded()) {        this.cachedInfo = onResponse.result();    }});if (cachedInfo != null) { // The value could be unset since the lambda is running in other thread     //end request}

Really don't know what to do, is there a way to return the contents of the AsyncResult to a variable or maybe set it to a variable synchronously somehow? I've also been searching for ways to somehow stop the whole flow of the current request but couldn't find any satisfactory, non-aggressive solution so far, but I'm really open to this option either.

Better Performance hget vs get || Using Redis

$
0
0

Better Performance hget vs get || Using Redis

1>hset key field value ---Here field("dept") will always be same(constant) and key could be 20 char

hset "user1""dept" 1hset "user2""dept" 2hset "user3""dept" 2

2>

set key value   --Here key could be 20 charset "{user1}dept" 1set "{user2}dept" 2set "{user3}dept" 3

Q1.In both cases which get cmd will run faster (considering our database has millions of key value pair)

hget "user2""dept"  vs  get "user2""dept"

Q2. is hset "user1""dept" 1 is equivalent to {"user1" : {"dept" : 1}} or {"dept" : {"user1" : 1}}

Q3. I want to implement expiry on key and field which is not possible in case of hset is there any alternative?

Using same Redis Cache for Inserting different Type Of Objects

$
0
0

Is it possible and right way to use same Redis cache for storing different type of objects? I know it supports multiple DS. In my scenario that object will be user defined objects. Moreover there will be 2 different methods that will be filling up same Redis cache with different type of keys like one is filling CustomerInfo against customerId and other is filling cache with AccountInfo against AccountId.

CacheConfig.class:

@Configurationpublic class CacheConfig extends AbstractCloudConfig {    @Autowired    Environment env;    @Bean    public RedisConnectionFactory brRedisFactory() {    return connectionFactory().redisConnectionFactory(env.getProperty("redis-cache"));    }    @Bean    public RedisTemplate<String, Object> brRedisTemplate() {        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();        redisTemplate.setConnectionFactory(brRedisFactory());        return redisTemplate;    }     @Bean(name = "myCacheMngr")     public CacheManager cacheManager() {        RedisCacheManager cacheManager = new RedisCacheManager(brRedisTemplate());        cacheManager.setUsePrefix(true);        cacheManager.setTransactionAware(true);        return cacheManager;    }}

Method for filling up Customer Data in Redis Cache. Will be having similar method for filling redis cache with Account Details against key 'accountId'.

@Cacheable(value="redis-cache",key ="#customerId")public FinancialPlanningDTO retriveCustomerdetails( String customerId, String modelId, String requestId) throws COException {    CustomerInfo csDTO;    try {        csDTO = csDTOAdapterImpl.        getCustomerDetails(customerId);    } catch (Exception e) {        e.printStackTrace();    }    return financialPlanningDTO;}

Spring Boot Redis error when dockerized, but not with maven run

$
0
0

I am building an application with Spring Boot using Redis (with redisson).

When I run my application in development mode, it works fine, but when I try to run it in docker containers, it fails with the error

java.lang.ClassNotFoundException:org.springframework.data.redis.connection.ReactiveStreamCommands

My maven configuration for Redis :

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.redisson</groupId><!-- for Spring Data Redis v.2.2.x --><artifactId>redisson-spring-data-22</artifactId><version>3.12.2</version></dependency>

My maven configuration to build docker container :

<plugin><groupId>com.spotify</groupId><artifactId>docker-maven-plugin</artifactId><version>1.2.1</version><dependencies><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency></dependencies><configuration><imageName>${imageName}</imageName><!-- default properties to tag an image --><image>${imageName}</image><newName>${imageName}:${tagName}</newName><!-- gitlab registry --><serverId>gitlab-repository</serverId><registryUrl>my.repository</registryUrl><baseImage>adoptopenjdk/openjdk11-openj9:latest</baseImage><entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint><!-- copy the service's jar file from target into the root directory                         of the image --><resources><resource><targetPath>/</targetPath><directory>${project.build.directory}</directory><include>${project.build.finalName}.jar</include></resource></resources></configuration></plugin>

When I login to my container and analysie my jar libraries (with the following command):

jar -tf my-app.jar | grep redis

I find this :

BOOT-INF/lib/spring-boot-starter-data-redis-2.1.3.RELEASE.jarBOOT-INF/lib/spring-data-redis-2.1.5.RELEASE.jarBOOT-INF/lib/redisson-spring-data-22-3.12.2.jarBOOT-INF/lib/redisson-3.12.2.jar

Which is exactly the same as I get with my jar for development.

Here is the docker-compose extract on how I launch redis :

  redis:    image: redis:5.0    ports:      - 6379:6379    networks:      - network    volumes:      - redis:/data    entrypoint: redis-server --appendonly yes     restart: unless-stopped

Any clue on what is missing for my container to run properly?Any idea why the spring-data-redis used in the jar is 2.1.5 and not 2.2.x ?Thanks in advance

Unable to connect to Jedis in AndroidStudio (Java)

$
0
0

My apllication is crushing when I press the button which is responsible for connecting to Redis database using Jedis client and changing TextView to value which stores jedis.ping() (It should return "Pong"). Code and Log are below. Same operations (connection to Redis and printing jedis.ping()) works perfectly in Eclipse. Maybe I insert code connected with Jedis in wrong place? I know too litle about Android programming. Thanks in advance!

package com.samfoundation.samfoundation;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;import redis.clients.jedis.Jedis;public class MainActivity extends AppCompatActivity {    Button click;    TextView show;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        click = (Button)findViewById(R.id.button);        show = (TextView)findViewById(R.id.textView);        click.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Jedis jedis = new Jedis("localhost");                String value = jedis.ping();                show.setText(value);            }        });    }}

Log:

2020-04-09 19:53:22.473 32666-32666/com.samfoundation.samfoundation E/AndroidRuntime: FATAL EXCEPTION: main    Process: com.samfoundation.samfoundation, PID: 32666    redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host localhost:6379        at redis.clients.jedis.Connection.connect(Connection.java:204)        at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:100)        at redis.clients.jedis.Connection.sendCommand(Connection.java:125)        at redis.clients.jedis.Connection.sendCommand(Connection.java:120)        at redis.clients.jedis.BinaryClient.ping(BinaryClient.java:113)        at redis.clients.jedis.BinaryJedis.ping(BinaryJedis.java:188)        at com.samfoundation.samfoundation.MainActivity$1.onClick(MainActivity.java:33)        at android.view.View.performClick(View.java:7259)        at android.view.View.performClickInternal(View.java:7236)        at android.view.View.access$3600(View.java:801)        at android.view.View$PerformClick.run(View.java:27892)        at android.os.Handler.handleCallback(Handler.java:883)        at android.os.Handler.dispatchMessage(Handler.java:100)        at android.os.Looper.loop(Looper.java:214)        at android.app.ActivityThread.main(ActivityThread.java:7356)        at java.lang.reflect.Method.invoke(Native Method)        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)     Caused by: java.net.SocketException: socket failed: EACCES (Permission denied)        at java.net.Socket.createImpl(Socket.java:492)        at java.net.Socket.getImpl(Socket.java:552)        at java.net.Socket.setReuseAddress(Socket.java:1493)        at redis.clients.jedis.Connection.connect(Connection.java:171)        at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:100)         at redis.clients.jedis.Connection.sendCommand(Connection.java:125)         at redis.clients.jedis.Connection.sendCommand(Connection.java:120)         at redis.clients.jedis.BinaryClient.ping(BinaryClient.java:113)         at redis.clients.jedis.BinaryJedis.ping(BinaryJedis.java:188)         at com.samfoundation.samfoundation.MainActivity$1.onClick(MainActivity.java:33)         at android.view.View.performClick(View.java:7259)         at android.view.View.performClickInternal(View.java:7236)         at android.view.View.access$3600(View.java:801)         at android.view.View$PerformClick.run(View.java:27892)         at android.os.Handler.handleCallback(Handler.java:883)         at android.os.Handler.dispatchMessage(Handler.java:100)         at android.os.Looper.loop(Looper.java:214)         at android.app.ActivityThread.main(ActivityThread.java:7356)         at java.lang.reflect.Method.invoke(Native Method)         at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.samfoundation.samfoundation"><application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

converting byte array to double in lua

$
0
0

Redis (a key-value store) supports lua scripts - it executes the script on the server. I am interacting with Redis using a java client. I am passing a byte array to lua and in lua, I would have to convert that to a int or string.

The following is the java code snippet

byte[] exclScore = ByteBuffer.allocate(8).putDouble(1.5).array();args.add(exclScore);

args is an ArrayList of type byte[]

Following is the lua script that I tried

byteScore = table.remove(ARGV)size = string.len(byteScore)x = string.sub(byteScore,1,1)local output = 0for i = 1,size do  bit = tonumber(string.sub(byteScore,i,1))  val2 = bit * (2 ^ i)  output = output + val2endreturn output

ARGV is the table which receives all the arguments sent by the java client and the score is the last entry. I checked the type(byteScore) and it turned out to be string. tonumber() returns a nil (which is the error I get, since I multiply it by 2)

Is there anyway in which we can convert this byte array into double or string representation of that double (1.5) in lua? Note that, we cannot use any external lua libraries inside redis scripts.

Any help is appreciated. Thanks in advance.


How to clear records from Redis Stream, left only N newest ones?

$
0
0

I have SpringBoot app where microservices send and receive some data from redis stream. So, every service send record which is Map:

StringRedisTemplate redisTemplate = new StringRedisTemplate();Map<String, String> recordMap = new HashMap<>();recordMap.put("topic", "topicName");recordMap.put("user", "John");recordMap.put("somethingElse", "someData");redisTemplate.opsForStream().add(            StreamRecords.newRecord()                .in("name_of_stream")                .ofMap(recordMap)))

Other services have

public class RedisMessagesListener implements StreamListener<String, MapRecord<String, String, String>>

which is triggered on each message in Redis, looks for "topic" value in record and do some staff.

The problem is that records, once sent to Redis Stream, are always stored by Redis.

Question is: I'm about to create @Scheduled method in Java. I need to delete old records of certain topics, left only N newest records (e.g., 1 000 000). How can I do that?

P.S. Sorry, I'm very beginner with Redis.

How to convert Java Hashmap Hierarchy to its equivalent in Redis Cache?

$
0
0

I have the following Job class representing runs of a job. I have a list of start and end times in Job class because the same Job can be rerun.

public class Job {      private final List<Timestamp> jobStartTimes = new SortedList<>();      private final List<Timestamp> jobEndTimes = new SortedList<>();      private String jobName;      private String jobKey;      private String host;      ....      ....}

I have this Map for querying jobs given jobkey.

public class JobMap {         /**         * Here value of 'String' key is jobKey         */         private final Map<String, Job> jobCache;}

I have also created the following hierarchy of hashmaps for storing (starttime, jobKey) and (endtime, jobkey) entries in Map so that I can retrieve job records faster. This is needed because my queries are timestamp based, for ex: return all jobs that ran between x and y timestamp.

public class YearCache<T> {        /**         * Here value of 'Integer' key is month number (0, 11)         */        private final Map<Integer, MonthCache> monthCache;}public class MonthCache {        /**         * Here value of 'Integer' key is week number in a month(0, 4)         */        private final Map<Integer, WeekCache> weekCache;}public class WeekCache {        /**         * Here value of 'Integer' key is day number in a week (0, 6)         */        private final Map<Integer, DayCache> dayCache;}private class DayCache{        /**         * Here value of 'Integer' key is hour value in a day (0, 23)         * T is of type String representing jobKey         */         private final NavigableMap<Integer, NavigableMap<Timestamp, Set<T>>> hourCache;}

I want to get rid of this Java hashmaps and move to Redis Cache. How can I model this hierarchy in Redis Cache?

How to connect to a Docker Redis cluster instance using jedis for Java?

$
0
0

I have created a cluster of 6 nodes using redis docker-compose (3 master and 3 slave) and also linked all of them.cluster info

cluster_state:okcluster_slots_assigned:16384cluster_slots_ok:16384cluster_slots_pfail:0cluster_slots_fail:0cluster_known_nodes:5cluster_size:3cluster_current_epoch:6cluster_my_epoch:1cluster_stats_messages_ping_sent:23cluster_stats_messages_pong_sent:31cluster_stats_messages_meet_sent:1cluster_stats_messages_sent:55cluster_stats_messages_ping_received:26cluster_stats_messages_pong_received:24cluster_stats_messages_meet_received:5cluster_stats_messages_received:55

cluster nodes

d794a9ab002f0c3cb699ce68a09310dd0fdb17de 192.168.65.3:32789@32783 slave c6c05515c3be01a1438b6d2aad823c0fa50b1743 0 1586629088989 5 connected7d4fab850bcfac8754a559c5e9469698b7f182bc 192.168.65.3:32792@32787 master - 0 1586629087000 2 connected 5461-10922c6c05515c3be01a1438b6d2aad823c0fa50b1743 192.168.65.3:32793@32788 master - 0 1586629089995 4 connected 10923-16383229b9b4f919f79a1c24b7b849c42acb9e3378532 192.168.65.3:32790@32785 slave 9b649a67dc53084ed7416b20e8bab00289e636d2 0 1586629089000 6 connected9b649a67dc53084ed7416b20e8bab00289e636d2 192.168.65.3:32791@32786 myself,master - 0 1586629086000 1 connected 0-5460

As shown above the cluster seems to be working but when I try to call the cluster instance in a java application using jedis by using the code

jedis = new JedisCluster(new HostAndPort("0.0.0.0", 32790));jedis.set("events/city/rome", "32,15,223,828");

then I get the following error

Exception in thread "main" redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException: No more cluster attempts left.    at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:86)    at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:124)    at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:124)    at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:124)    at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:124)    at redis.clients.jedis.JedisClusterCommand.runWithRetries(JedisClusterCommand.java:124)    at redis.clients.jedis.JedisClusterCommand.run(JedisClusterCommand.java:25)    at redis.clients.jedis.JedisCluster.set(JedisCluster.java:112)    at sc.dev.algordf.ALGORDF.main(ALGORDF.java:53)

Please help me find out what could be the problem. Is it because I have not specified the right IP and port number when creating a jedis instance. Or is it something that I am missing.

Thanks.

Mock redis template

$
0
0

I am facing a issue in mock redis template.Can any one help me to write unit test for below class.

@Repositorypublic class CasheRepo {    @Autowired    private RedisTemplate<String, Object> template;    public Object getObject(final String key) {    return template.opsForValue().get(key);    }}

And below is unit test class. But it is not working. It shows null point exceptions

@RunWith(MockitoJUnitRunner.class)public class CashRepoTest {    @InjectMocks    private CasheRepo casheRepo = new CasheRepo();    private @Mock RedisConnection redisConnectionMock;    private @Mock RedisConnectionFactory redisConnectionFactoryMock;    private RedisTemplate redisTemplate;    @Before    public void setUp() {   Mockito.when(redisConnectionFactoryMock.getConnection()).thenReturn(redisConnectionMock);       redisTemplate = new RedisTemplate();    redisTemplate.setConnectionFactory(redisConnectionFactoryMock);    redisTemplate.afterPropertiesSet();    }    @Test    public void getObjectTest() {    Mockito.doNothing().when(redisTemplate).opsForValue().set("spring", "data");    redisTemplate.afterPropertiesSet();      System.out.println(redisTemplate.opsForValue().get("spring"));       }    }

Redis PubSub Reconnect with Jedis

$
0
0

Trying to include the code related to azure redis autoreconnect if any network error occurred in Redis PubSub connection. Any help/advice would be appreciable. Below is my Redis Config code.

 public class RedisConfig    {        @Bean    JedisConnectionFactory jedisConnectionFactory() {        JedisConnectionFactory jedis = new JedisConnectionFactory();        jedis.setHostName("redishostname");        jedis.setPassword("redispassword");        jedis.setPort(redisport);        return jedis;    }    @Bean    public RedisTemplate<String, Object> redisTemplate() {        final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();        template.setConnectionFactory(jedisConnectionFactory());        template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));        return template;    }       @Bean    RedisMessageListenerContainer redisContainer() {        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();        container.setConnectionFactory(jedisConnectionFactory());        container.setTaskExecutor(Executors.newFixedThreadPool(4));             return container;    }    }

Spring Data Redis Expire Key

$
0
0

I have a One Spring Hibernate Application. In my application, Recently i am implemented Spring data Redis.

spring-servlet.xml<!-- redis connection factory --><bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true"/><!-- redis template definition --><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"    p:connection-factory-ref="jedisConnFactory"/>

And this redisTemplate use in my ServiceImpl class.

RedisServiceImpl@Autowiredprivate RedisTemplate<String, T> redisTemplate;public RedisTemplate<String, T> getRedisTemplate() {    return redisTemplate;}public void setRedisTemplate(RedisTemplate<String, T> redisTemplate) {    this.redisTemplate = redisTemplate;}

Now I added data in redisServer like this

public void putData(String uniqueKey, String key, Object results) {    redisTemplate.opsForHash().put(uniqueKey, key, results);}

Now i want to remove Expire key.

I search in Google, But in google all are saying like this

redisTemplate.expire(key, timeout, TimeUnit);

In this expire method, We need to provide uniqueKey instead of key.But I need to Expire key instead of uniqueKey.

So Please help me what can i do for expire Key?

Spring nested @CacheEvict

$
0
0

Suppose I have these two classes:

public class A implements Serializable {    ...    public B b;    public String name;}public class B implements Serializable {    ...    public int value;}

And I have two services:

@Servicepublic class ServiceA {    @Autowired    ServiceB serviceB;    @Cacheable(cacheNames = "cacheA")    public A createA(int bId, String name){        A a = new A();        B b = serviceB.findById(bId);        a.setName(name);        a.setB(b);        return a;    }}@Servicepublic class ServiceB {    @Cacheable(cacheNames = "cacheB")    public B findById(int id) {        return repositoryB.findById(id);    }    @CacheEvict(cacheNames = "cacheB")    public void incrementValueById(int id){        B b = repositoryB.findById(id);        b.value++;        repositoryB.save(b);    }}

And then I called method createA(1, "some name") of ServiceA and got this cached in cacheA:

{"name": "some name","b": {"value": 0    }}

And in cache cacheB I got:

{"value": 0}

If I call incrementValueById of ServiceB I clear cacheB, and when I call findById of ServiceB, I get and cache refreshed data. I want to clear cache cacheA also, because it now has outdated data of B. How can I do that? Thank you!


Caching selected hibernate entities in Redis Cache without using Redis as second level cache

$
0
0

We already have ehcache as a Hibernate second level cache. I want to maintain a remote cache for the entities which are less frequently updated, but any update need to be reflected quickly on all instances of the application. I have gone through lot of documentation which use Redis as second level cache using clients like Reddison. But I don't want to use Redis as second level cache but for few entities to be cached in Redis and any update to them should be reflected immediately in remote cache on any update in cached entities. Is there anyway to achieve this using Reddison?

How to add a list to a redis list? [closed]

$
0
0

I have to add a list to an exsiting list in Redis,for adding to redis list action is happening synchroniselly, if add element to list one by one, the sequence of a complete list will be interrupt.

What's the solution?

Redis ErrnoException in running server

$
0
0

I am getting Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)when trying to connect to my redis server in AndroidStudio. Server has already been started and status shows that it works well in terminal (green light, active: running, PONG to jedis.ping() in redis-cli -p 6381 (I use 6381 port)). I thought I might have written false ip and port in Jedis jedis = new Jedis("127.0.0.1",6381); but sudo lsof -i -P -n | grep LISTEN says redis-ser 28687 redis 6u IPv4 258387 0t0 TCP 127.0.0.1:6381 so it seems like IP and port are correct. For this reason, I'm still wonder why I got that exception. For sure, it is my stupid error, but I can't find it out where it is. There is Internet permission in Android Manifest as well. So my code is below, but I'm not sure that the reason is in code:

package com.samfoundation.samfoundation;import android.os.AsyncTask;import redis.clients.jedis.Jedis;public class Connection extends AsyncTask<Void, Void, String> {    String value;    @Override    protected String doInBackground(Void... arg0) {        Jedis jedis = new Jedis("127.0.0.1",6381);        value = jedis.ping();        return value;    }}public class MainActivity extends AppCompatActivity {    Button click;    TextView show;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        click = (Button)findViewById(R.id.button);        show = (TextView)findViewById(R.id.textView);        Connection con = new Connection();        con.execute();        final String message = con.value;        click.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                show.setText(message);            }        });    }}

Write many, ready many data store?

$
0
0

I have an application that does over 10,000 TPS. I'd like to do 3 things. I check if the key exists in our data structure, if it does then I grab that key and the data associated with it and push it in a Java object. Before the object is built, it processes the data and creates the object. Once it processes everything, the values of the object are then pushed back in the data structure. If the key does not exist in the data structure, then the key gets created.

As you can see, this implementation has the same amount of writes as reads. Before, I was using a Java hashmap as the data structure, now I was looking into Redis. However, I'm not sure if Redis is the best choice because Redis is best used as a cache. What kind of data structure would handle this amount of volume and get a response back for each transaction?

How compareAndSet works internally in redis

$
0
0

spring-data-redis module contains RedisAtomicLong class.

In this class you can see

public boolean compareAndSet(long expect, long update) {    return generalOps.execute(new SessionCallback<Boolean>() {        @Override        @SuppressWarnings("unchecked")        public Boolean execute(RedisOperations operations) {            for (;;) {                operations.watch(Collections.singleton(key));                if (expect == get()) {                    generalOps.multi();                    set(update);                    if (operations.exec() != null) {                        return true;                    }                }                {                    return false;                }            }        }    });}

My question is why it works?

generalOps.multi() starts transaction after get() is invoked. It means that there is possibility that two different thread (or even client) can change value and both of them will succeed.

Is operations.watch prevent it somehow? JavaDoc doesn't explain purpose of this method.

PS: Minor question: why for (;;)? There is always one iteration.

Viewing all 2203 articles
Browse latest View live


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