kandi background
Explore Kits

redisson | Redisson Redis Java client with features of InMemory Data Grid

 by   redisson Java Version: redisson-3.16.8 License: Apache-2.0

 by   redisson Java Version: redisson-3.16.8 License: Apache-2.0

Download this library from

kandi X-RAY | redisson Summary

redisson is a Java library typically used in Telecommunications, Media, Media, Entertainment applications. redisson has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
[Quick start](https://github.com/redisson/redisson#quick-start) | [Documentation](https://github.com/redisson/redisson/wiki/Table-of-Content) | [Changelog](https://github.com/redisson/redisson/blob/master/CHANGELOG.md) | [Code examples](https://github.com/redisson/redisson-examples) | [FAQs](https://github.com/redisson/redisson/wiki/16.-FAQ) | [Report an issue](https://github.com/redisson/redisson/issues/new). Based on high-performance async and lock-free Java Redis client and [Netty](http://netty.io) framework. JDK compatibility: 1.8 - 17, Android.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • redisson has a highly active ecosystem.
  • It has 18262 star(s) with 4453 fork(s). There are 884 watchers for this library.
  • There were 7 major release(s) in the last 12 months.
  • There are 232 open issues and 3426 have been closed. On average issues are closed in 29 days. There are 29 open pull requests and 0 closed requests.
  • It has a negative sentiment in the developer community.
  • The latest version of redisson is redisson-3.16.8
redisson Support
Best in #Java
Average in #Java
redisson Support
Best in #Java
Average in #Java

quality kandi Quality

  • redisson has 0 bugs and 0 code smells.
redisson Quality
Best in #Java
Average in #Java
redisson Quality
Best in #Java
Average in #Java

securitySecurity

  • redisson has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • redisson code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
redisson Security
Best in #Java
Average in #Java
redisson Security
Best in #Java
Average in #Java

license License

  • redisson is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
redisson License
Best in #Java
Average in #Java
redisson License
Best in #Java
Average in #Java

buildReuse

  • redisson releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • redisson saves you 184408 person hours of effort in developing the same functionality from scratch.
  • It has 217224 lines of code, 23440 functions and 2038 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
redisson Reuse
Best in #Java
Average in #Java
redisson Reuse
Best in #Java
Average in #Java
Top functions reviewed by kandi - BETA

kandi has reviewed redisson and discovered the below as its top functions. This is intended to give you an instant insight into redisson implemented functionality, and help decide if they suit your requirements.

  • Executes a Redis based queue of commands .
  • Attempt to lock the redis in the redis .
  • Asynchronously put value in cache .
  • Traverse AND conditions .
  • Initialize Redisson library .
  • Disables local caches asynchronously .
  • Initialize ssl configuration
  • Delete value .
  • Try to handle a single object .
  • Add a master to the cluster

redisson Key Features

Redis Replicated setup (including support of [AWS ElastiCache](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Replication.html) and [Azure Redis Cache](https://azure.microsoft.com/en-us/services/cache/))

Redis Cluster setup (including support of [AWS ElastiCache Cluster](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Clusters.html) and [Azure Redis Cache](https://azure.microsoft.com/en-us/services/cache/))

Redis Sentinel setup

Redis with Master with Slave only

Redis single (including support of [Azure Redis Cache](https://azure.microsoft.com/en-us/services/cache/) and [Google Cloud Memorystore for Redis](https://cloud.google.com/memorystore/docs/redis/))

Thread-safe implementation

[Reactive Streams](https://github.com/redisson/redisson/wiki/3.-operations-execution#32-reactive-way) API

[RxJava3](https://github.com/redisson/redisson/wiki/3.-operations-execution#32-reactive-way) API

[Asynchronous](https://github.com/redisson/redisson/wiki/3.-operations-execution#31-async-way) API

Asynchronous connection pool

Lua scripting

Local cache support including [Caffeine](https://github.com/ben-manes/caffeine)-based implementation

[Distributed Java objects](https://github.com/redisson/redisson/wiki/6.-Distributed-objects) Object holder, Binary stream holder, Geospatial holder, BitSet, AtomicLong, AtomicDouble, PublishSubscribe, Bloom filter, HyperLogLog

[Distributed Java collections](https://github.com/redisson/redisson/wiki/7.-Distributed-collections) Map, Multimap, Set, List, SortedSet, ScoredSortedSet, LexSortedSet, Queue, Deque, Blocking Queue, Bounded Blocking Queue, Blocking Deque, Delayed Queue, Priority Queue, Priority Deque

[Distributed Java locks and synchronizers](https://github.com/redisson/redisson/wiki/8.-Distributed-locks-and-synchronizers) Lock, FairLock, MultiLock, RedLock, ReadWriteLock, Semaphore, PermitExpirableSemaphore, CountDownLatch

[Distributed services](https://github.com/redisson/redisson/wiki/9.-distributed-services) Remote service, Live Object service, Executor service, Scheduler service, MapReduce service

[Helidon](https://github.com/redisson/redisson/tree/master/redisson-helidon) integration

[Micronaut](https://github.com/redisson/redisson/tree/master/redisson-micronaut) integration

[Quarkus](https://github.com/redisson/redisson/tree/master/redisson-quarkus) integration

[Spring Cache](https://github.com/redisson/redisson/wiki/14.-Integration-with-frameworks/#142-spring-cache) implementation

[Spring Transaction API](https://github.com/redisson/redisson/wiki/14.-Integration-with-frameworks/#148-spring-transaction-manager) implementation

[Spring Data Redis](https://github.com/redisson/redisson/tree/master/redisson-spring-data) integration

[Spring Boot Starter](https://github.com/redisson/redisson/tree/master/redisson-spring-boot-starter) implementation

[Hibernate Cache](https://github.com/redisson/redisson/tree/master/redisson-hibernate) implementation

[MyBatis Cache](https://github.com/redisson/redisson/tree/master/redisson-mybatis) implementation

[Transactions API](https://github.com/redisson/redisson/wiki/10.-Additional-features#104-transactions)

[JCache API (JSR-107)](https://github.com/redisson/redisson/wiki/14.-Integration-with-frameworks/#144-jcache-api-jsr-107-implementation) implementation

[Tomcat Session Manager](https://github.com/redisson/redisson/tree/master/redisson-tomcat) implementation

[Spring Session](https://github.com/redisson/redisson/wiki/14.-Integration-with-frameworks/#147-spring-session) implementation

[Redis pipelining](https://github.com/redisson/redisson/wiki/10.-additional-features#103-execution-batches-of-commands) (command batches)

Supports Android platform

Supports auto-reconnection

Supports failed to send command auto-retry

Supports OSGi

Supports SSL

Supports many popular codecs ([JBoss Marshalling](https://github.com/jboss-remoting/jboss-marshalling), [Jackson JSON](https://github.com/FasterXML/jackson), [Avro](http://avro.apache.org/), [Smile](http://wiki.fasterxml.com/SmileFormatSpec), [CBOR](http://cbor.io/), [MsgPack](http://msgpack.org/), [Kryo](https://github.com/EsotericSoftware/kryo), [Amazon Ion](https://amzn.github.io/ion-docs/), [LZ4](https://github.com/jpountz/lz4-java), [Snappy](https://github.com/xerial/snappy-java) and JDK Serialization)

With over 2000 unit tests <!-- Used by

Features

copy iconCopydownload iconDownload
// 1. Create config object
Config config = new Config();
config.useClusterServers()
       // use "rediss://" for SSL connection
      .addNodeAddress("redis://127.0.0.1:7181");

// or read config from file
config = Config.fromYAML(new File("config-file.yaml"));

Redisson Hibernate 2L cache setup but always executes SQL query

copy iconCopydownload iconDownload
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import javax.persistence.QueryHint;

import static org.hibernate.jpa.QueryHints.HINT_CACHEABLE;

@Repository
public interface EmployeeRepository extends CrudRepository<EmployeeEntity, Long> {

    @QueryHints(value = { @QueryHint(name = HINT_CACHEABLE, value = "true")})
    EmployeeEntity findByEmployeeId(Long employeeId);

}

how to configure the key expired event listener in redisson reactive api (spring boot project)

copy iconCopydownload iconDownload

        this.client
                .getPatternTopic("__keyevent@*__:expired", StringCodec.INSTANCE)
                .addListener(String.class, new PatternMessageListener<String>() {
                    @Override
                    public void onMessage(CharSequence pattern, CharSequence channel, String msg) {
                        System.out.println("pattern = " + pattern + ", channel = " + channel + ", msg = " + msg);
                    }
                })
                .subscribe();

How to execute plain Redis queries in Java

copy iconCopydownload iconDownload
Object sendCommand(ProtocolCommand cmd, byte[]... args)
Object sendCommand(ProtocolCommand cmd, String... args)
public enum Command implements ProtocolCommand {
  
  FT_SEARCH("FT.SEARCH");
  
  private final byte[] raw;
  
  private Command(String str) {
    raw = str.getBytes();
  }
  
  @Override
  public byte[] getRaw() {
    return raw;
  }
}
jedis.sendCommand(Command.FT_SEARCH, "SOME_INDEX", "(@foo:bar*)");
-----------------------
Object sendCommand(ProtocolCommand cmd, byte[]... args)
Object sendCommand(ProtocolCommand cmd, String... args)
public enum Command implements ProtocolCommand {
  
  FT_SEARCH("FT.SEARCH");
  
  private final byte[] raw;
  
  private Command(String str) {
    raw = str.getBytes();
  }
  
  @Override
  public byte[] getRaw() {
    return raw;
  }
}
jedis.sendCommand(Command.FT_SEARCH, "SOME_INDEX", "(@foo:bar*)");
-----------------------
Object sendCommand(ProtocolCommand cmd, byte[]... args)
Object sendCommand(ProtocolCommand cmd, String... args)
public enum Command implements ProtocolCommand {
  
  FT_SEARCH("FT.SEARCH");
  
  private final byte[] raw;
  
  private Command(String str) {
    raw = str.getBytes();
  }
  
  @Override
  public byte[] getRaw() {
    return raw;
  }
}
jedis.sendCommand(Command.FT_SEARCH, "SOME_INDEX", "(@foo:bar*)");

Change logging level in redisson

copy iconCopydownload iconDownload
<logger name="org.redisson" level="INFO" />

socketio.emit doesn't work netty socketio

copy iconCopydownload iconDownload
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.19</version>
        </dependency>
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>
-----------------------
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.19</version>
        </dependency>
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>
-----------------------
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.19</version>
        </dependency>
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>

liberty:devc: &lt;dockerfile&gt; not being honored

copy iconCopydownload iconDownload
      <plugin>
        <groupId>io.openliberty.tools</groupId>
        <artifactId>liberty-maven-plugin</artifactId>
        <version>3.3.4</version>
        <configuration>
          <dockerfile>/home/edburns/workareas/open-liberty-on-aks/javaee-app-redisson/target/Dockerfile</dockerfile>
          <!-- ... rest of config ... -->
        </configuration>
      </plugin>

How to listen redis list event with redisson and ZIO

copy iconCopydownload iconDownload
val redisson = Redisson.create()    
val bqueue : RQueue[String] = redisson.getQueue("minio_events", new StringCodec())
    
val pollQueue = 
  ZIO
    .effect(Option(bqueue.poll())) // RQueue.poll returns null if the queue is empty
    .someOrFail(NoElementsOnStream)
ZStream
  .fromEffect(pollQueue)
  .foreach(s => putStrLn(s))
  .exitCode
ZStream
  .fromEffect(pollQueue)
  .retry(Schedule.spaced(1.second))
  .forever
  .foreach(s => putStrLn(s))  
  .exitCode
-----------------------
val redisson = Redisson.create()    
val bqueue : RQueue[String] = redisson.getQueue("minio_events", new StringCodec())
    
val pollQueue = 
  ZIO
    .effect(Option(bqueue.poll())) // RQueue.poll returns null if the queue is empty
    .someOrFail(NoElementsOnStream)
ZStream
  .fromEffect(pollQueue)
  .foreach(s => putStrLn(s))
  .exitCode
ZStream
  .fromEffect(pollQueue)
  .retry(Schedule.spaced(1.second))
  .forever
  .foreach(s => putStrLn(s))  
  .exitCode
-----------------------
val redisson = Redisson.create()    
val bqueue : RQueue[String] = redisson.getQueue("minio_events", new StringCodec())
    
val pollQueue = 
  ZIO
    .effect(Option(bqueue.poll())) // RQueue.poll returns null if the queue is empty
    .someOrFail(NoElementsOnStream)
ZStream
  .fromEffect(pollQueue)
  .foreach(s => putStrLn(s))
  .exitCode
ZStream
  .fromEffect(pollQueue)
  .retry(Schedule.spaced(1.second))
  .forever
  .foreach(s => putStrLn(s))  
  .exitCode
-----------------------
object Test extends zio.App {
   def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] = 
       (for {
         // Construct the client in the scope of the stream so it shuts down when done
         c <- ZStream.managed(ZManaged.makeEffect(Redisson.create())(_.shutdown()))

         // Variant of effectAsync* that lets you specify an interrupter
         s <- ZStream.effectAsyncInterrupt[Any, Nothing, String] { k =>
           val queue = c.getQueue[String]("", new StringCodec())
           val listenerId = queue.addListener(new ListAddListener {

             // Invoke the callback by passing in a ZIO with a single chunk
             def onListAdd(name: String): Unit = k(ZIO.succeed(Chunk.single(name)))
           })

           // Return a cancellation handler.
           Left(UIO(queue.removeListener(listenerId)))
        }
      } { zio.console.putStrLn(s) }).exitCode
}

Issues with Upgrading Spring boot from 2.2.2.Release to 2.4.2 Rlease

copy iconCopydownload iconDownload
Importing spring-cloud-sleuth as a BOM for dependency management is very suspect.
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-sleuth</artifactId>
                <version>3.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
-----------------------
Importing spring-cloud-sleuth as a BOM for dependency management is very suspect.
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-sleuth</artifactId>
                <version>3.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
-----------------------
Importing spring-cloud-sleuth as a BOM for dependency management is very suspect.
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-sleuth</artifactId>
                <version>3.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
-----------------------
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
        <version>3.0.3</version>
    </dependency>

Redisson for JCache Session persistence on WebSphere-Liberty: how to pass redisson-jcache.yaml?

copy iconCopydownload iconDownload
cacheManager = cachingProvider.getCacheManager(uri, null, vendorProperties);
<logging traceSpecification="*=info:com.ibm.ws.session.store.cache.*=all"/>
-----------------------
cacheManager = cachingProvider.getCacheManager(uri, null, vendorProperties);
<logging traceSpecification="*=info:com.ibm.ws.session.store.cache.*=all"/>
-----------------------
clusterServerConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}
clusterServersConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}
Unrecognized field "clusterServerConfig" (class org.redisson.config.Config), not marked as ignorable (23 known properties: "eventLoopGroup", "maxCleanUpDelay", "nettyHook", "keepPubSubOrder", "nettyThreads", "threads", "transportMode", "singleServerConfig", "sentinelServersConfig", "reliableTopicWatchdogTimeout", "useScriptCache", "minCleanUpDelay", "connectionListener", "executor", "codec", "replicatedServersConfig", "clusterServersConfig", "useThreadClassLoader", "masterSlaveServersConfig", "addressResolverGroupFactory", "lockWatchdogTimeout", "cleanUpKeysAmount", "referenceEnabled"])
-----------------------
clusterServerConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}
clusterServersConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}
Unrecognized field "clusterServerConfig" (class org.redisson.config.Config), not marked as ignorable (23 known properties: "eventLoopGroup", "maxCleanUpDelay", "nettyHook", "keepPubSubOrder", "nettyThreads", "threads", "transportMode", "singleServerConfig", "sentinelServersConfig", "reliableTopicWatchdogTimeout", "useScriptCache", "minCleanUpDelay", "connectionListener", "executor", "codec", "replicatedServersConfig", "clusterServersConfig", "useThreadClassLoader", "masterSlaveServersConfig", "addressResolverGroupFactory", "lockWatchdogTimeout", "cleanUpKeysAmount", "referenceEnabled"])
-----------------------
clusterServerConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}
clusterServersConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}
Unrecognized field "clusterServerConfig" (class org.redisson.config.Config), not marked as ignorable (23 known properties: "eventLoopGroup", "maxCleanUpDelay", "nettyHook", "keepPubSubOrder", "nettyThreads", "threads", "transportMode", "singleServerConfig", "sentinelServersConfig", "reliableTopicWatchdogTimeout", "useScriptCache", "minCleanUpDelay", "connectionListener", "executor", "codec", "replicatedServersConfig", "clusterServersConfig", "useThreadClassLoader", "masterSlaveServersConfig", "addressResolverGroupFactory", "lockWatchdogTimeout", "cleanUpKeysAmount", "referenceEnabled"])

Redisson async procesing messages

copy iconCopydownload iconDownload
public class RedisListenerServiceImpl implements MessageListener<String> {

private static final Logger log = LoggerFactory.getLogger(RedisListenerServiceImpl.class);
private final ObjectMapper objectMapper = new ObjectMapper();
private final ExecutorService executorService = Executors.newFixedThreadPool(10);

@Override
public void onMessage(CharSequence channel, String stringMsg) {

    log.info("Message received: {}", stringMsg);
    MessageDto msg;
    try {
        msg = objectMapper.readValue(stringMsg, MessageDto.class);
        executorService.submit(()->{
        System.out.println("do something with message: "+msg);
    });
    } catch (final IOException e) {
        log.error("Unable to deserialize message: {}", e.getMessage(), e);
        return;
    }

    try {
        //Do my stuff
    } catch (Exception e) {
        log.error("Unable to get service from factory: {}", e.getMessage(), e);
    }

}

Community Discussions

Trending Discussions on redisson
  • Redisson Hibernate 2L cache setup but always executes SQL query
  • org.redisson.client.handler.PingConnectionHandler$1.run(PingConnectionHandler.java:79)
  • how to configure the key expired event listener in redisson reactive api (spring boot project)
  • Unable to connect to AWS ElastiCache form python client
  • How to execute plain Redis queries in Java
  • Change logging level in redisson
  • Invalidate cache (2LD Cache Hibernate) if add or remove column in entity. (reddison)
  • socketio.emit doesn't work netty socketio
  • How to get embedded Redis metrics?
  • liberty:devc: &lt;dockerfile&gt; not being honored
Trending Discussions on redisson

QUESTION

Redisson Hibernate 2L cache setup but always executes SQL query

Asked 2022-Mar-08 at 00:18

I'm trying to setup Redisson Hibernate 2L caching but I'm seeing the hibernate query execute every time even though the results are clearly cached on my Redis instance.

When debugging I can see it goes through hibernate and does the query execution and then after it goes into the putIntoCache from RedissonStorage.java as expected. When I check Redis I can see the new cached values. However, on a subsequent call to my service it again goes through the hibernate executeQueryStatement for the the exact same hibernate query but interestingly it then goes into the getFromCache from RedissonStorage.java and appears to return the value from Redis. Why is it executing the query every time and not actually checking redis first?

appliation.yml

spring.profiles.active: local

server:
  port: 9000

spring:
  config:
    active:
      on-profile: local
  cache:
    type: redis

  jpa:
    database: POSTGRESQL
    generate-ddl: true
    properties:
      hibernate:
        jdbc:
          time_zone: UTC
        ddl-auto: create-drop
        show_sql: true
        cache:
          use_query_cache: true
          use_second_level_cache: true
          factory_class: org.redisson.hibernate.RedissonRegionFactory
          redisson:
            fallback: true
            config: redisson/redisson.yml
  datasource:
    platform: postgres
    url: jdbc:postgresql://localhost:5432/test
    username: postgres
    password: admin
    driverClassName: org.postgresql.Driver
    initialization-mode: always

redisson.yml

singleServerConfig:
  address: "redis://localhost:6379"

build.gradle

plugins {
    id 'org.springframework.boot' version '2.6.4'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.test'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-cache:2.6.4'

    implementation 'org.redisson:redisson-hibernate-53:3.16.8'

    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'org.postgresql:postgresql'

    compileOnly 'org.apache.logging.log4j:log4j-api:2.17.1'
    compileOnly 'org.apache.logging.log4j:log4j-core:2.17.1'

    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

Entity class

@Data
@Entity
@Table(name = "employees")
@Cacheable
@Cache(region = "employeeCache", usage = CacheConcurrencyStrategy.READ_WRITE)
public class EmployeeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long employeeId;

    private String employeeName;
    private String employeeLastName;
}
@Component
public class EmployeeDAO {

    @Autowired
    private EmployeeRepository employeeRepository;

    public EmployeeEntity findByEmployeeId(Long employeeId) {
        return employeeRepository.findByEmployeeId(employeeId);
    }
@Repository
public interface EmployeeRepository extends CrudRepository<EmployeeEntity, Long> {

    EmployeeEntity findByEmployeeId(Long employeeId);
}

ANSWER

Answered 2022-Mar-08 at 00:18

Well looks like JPA caching will work for the default findById but will not work for findAll or a custom findByType or in this case findByEmployeeId.

However, I found a way to make it work by use of @QueryHints.

import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import javax.persistence.QueryHint;

import static org.hibernate.jpa.QueryHints.HINT_CACHEABLE;

@Repository
public interface EmployeeRepository extends CrudRepository<EmployeeEntity, Long> {

    @QueryHints(value = { @QueryHint(name = HINT_CACHEABLE, value = "true")})
    EmployeeEntity findByEmployeeId(Long employeeId);

}

Source https://stackoverflow.com/questions/71366009

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install redisson

You can download it from GitHub, Maven.
You can use redisson like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the redisson component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Reuse Pre-built Kits with redisson
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.