Prerequisite: Build a redis cluster environment. Please see the construction method: https://www.VeVB.COM/article/143749.htm
1. Create a new project and add redis support to the pom.xml file
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>
2. Configure application.properties
spring.redis.cluster.nodes=127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384,127.0.0.1:6385spring.redis.cluster.timeout=1000spring.redis.cluster.max-redirects=3
3. Create the following two classes
@Configurationpublic class RedisConfiguration { @Resource private LettuceConnectionFactory myLettuceConnectionFactory; @Bean public RedisTemplate<String, Serializable> redisTemplate() { RedisTemplate<String, Serializable> template = new RedisTemplate<>(); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setConnectionFactory(myLettuceConnectionFactory); return template; }} @Configurationpublic class RedisFactoryConfig { @Autowired private Environment environment; @Bean public RedisConnectionFactory myLettuceConnectionFactory() { Map<String, Object> source = new HashMap<String, Object>(); source.put("spring.redis.cluster.nodes", environment.getProperty("spring.redis.cluster.nodes")); source.put("spring.redis.cluster.timeout", environment.getProperty("spring.redis.cluster.timeout")); source.put("spring.redis.cluster.max-redirects", environment.getProperty("spring.redis.cluster.max-redirects")); RedisClusterConfiguration redisClusterConfiguration; redisClusterConfiguration = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source)); return new LettuceConnectionFactory(redisClusterConfiguration); }}4. Perform tests
@SpringBootTest@RunWith(SpringRunner.class)public class RedisConfigurationTest { @Autowiredprivate RedisTemplate redisTemplate;@Testpublic void redisTemplate() throws Exception { redisTemplate.opsForValue().set("author", "Damein_xym");}} 5. Verify that use Redis Desktop Manager to connect to the redis node and check whether the data inside exists as an author. The following shows it, and it proves successful.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.