In-depth analysis of how springboot configures multiple redis connections
Spring Boot provides automatic configuration for Redis, MongoDB, Elasticsearch, Solr and Gemfire. This article introduces in detail the configuration of multiple redis connections in springboot. Those who are interested can learn more.
1. springboot nosql Introduction
Spring Data provides other projects to help you use various NoSQL technologies including MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire, Couchbase and Cassandra. Spring Boot provides automatic configuration for Redis, MongoDB, Elasticsearch, Solr and Gemfire. You can take full advantage of other projects, but you need to configure them yourself.
1.1. Redis
Redis is a cache, message middleware and key-value storage system with rich features . Spring Boot provides automatic configuration for the Jedis client library and the Jedis client-based abstractions provided by Spring Data Redis. spring-boot-starter-redis 'Starter POM' provides a convenient way to collect dependencies.
Redis adds maven dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <!-- <version>1.3.5.RELEASE</version> --> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <!-- <version>1.3.6.RELEASE</version> --> </dependency>
1.2 Connecting to Redis
You can inject an automatically configured RedisConnectionFactory, StringRedisTemplate or an ordinary RedisTemplate instance that is the same as other Spring Beans . By default, this instance will try to connect to the Redis server using localhost:6379.
@Component public class MyBean { private StringRedisTemplate template; @Autowired public MyBean(StringRedisTemplate template) { this.template = template; } // ... }
If you add a @Bean of your own of any auto-configuration type, it will replace the default one (except in the case of RedisTemplate, which is excluded based on the bean's name 'redisTemplate' rather than its type ). If commons-pool2 exists in the classpath, you will get a connection pool factory by default.
1.3 Establish multiple redis connections
Use the default configuration of redis to connect to library 0 in redis. If you specify a library connection, you need to configure indexdb. At the same time, if you need to connect to multiple redis services, you also need to configure multiple data sources at the same time
1.3.1. Add:
@Component public class MyBean { private StringRedisTemplate template; @Autowired public MyBean(StringRedisTemplate template) { this.template = template; } // ... }
1.3.2. Create redisconfiguration
@Configuration public class Redis137_11Configuration { @Bean(name = "redis123Template") public StringRedisTemplate redisTemplate( @Value("${redis123.hostName}") String hostName, @Value("${redis123.port}") int port, @Value("${redis123.password}") String password, @Value("${redis123.maxIdle}") int maxIdle, @Value("${redis123.maxTotal}") int maxTotal, @Value("${redis123.index}") int index, @Value("${redis123.maxWaitMillis}") long maxWaitMillis, @Value("${redis123.testOnBorrow}") boolean testOnBorrow) { StringRedisTemplate temple = new StringRedisTemplate(); temple.setConnectionFactory(connectionFactory(hostName, port, password, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow)); return temple; } public RedisConnectionFactory connectionFactory(String hostName, int port, String password, int maxIdle, int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) { JedisConnectionFactory jedis = new JedisConnectionFactory(); jedis.setHostName(hostName); jedis.setPort(port); if (!StringUtils.isEmpty(password)) { jedis.setPassword(password); } if (index != 0) { jedis.setDatabase(index); } jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, testOnBorrow)); // 初始化连接pool jedis.afterPropertiesSet(); RedisConnectionFactory factory = jedis; return factory; } public JedisPoolConfig poolCofig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) { JedisPoolConfig poolCofig = new JedisPoolConfig(); poolCofig.setMaxIdle(maxIdle); poolCofig.setMaxTotal(maxTotal); poolCofig.setMaxWaitMillis(maxWaitMillis); poolCofig.setTestOnBorrow(testOnBorrow); return poolCofig; } }
1.3.3. Declare the redis abstract base class and create the redis operation method
public abstract class AbRedisConfiguration { protected StringRedisTemplate temple; public void setData(String key, String value) { getTemple().opsForValue().set(key, value); } public String getData(String key) { return getTemple().opsForValue().get(key); } public StringRedisTemplate getTemple() { return temple; } }
1.3.4. Create different subclasses according to the data source @Component
public class Redis123 extends AbRedisConfiguration { @Resource(name = "redis123Template") private StringRedisTemplate temple; public StringRedisTemplate getTemple() { return temple; } }
ps: The getTemple method and StringRedisTemple attribute are declared in the class and subclass at the same time. The subclass passes the subclass's own StringRedisTemple attribute to the parent class by overriding the getTeimple method of the parent class, and the parent class passes it through the subclass. The StringRedisTemple uses different data links to operate the cache. At this point, the parent class has completed all operation methods, and when you need to create a database connection, you only need to create a subclass, declare its own StringRedisTemple, and pass it to the parent class.
The above is the detailed content of In-depth analysis of how springboot configures multiple redis connections. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.