最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Redis的哨兵模式的實(shí)現(xiàn)

 更新時(shí)間:2024年08月19日 09:46:20   作者:牛肉胡辣湯  
Redis提供了哨兵模式來(lái)處理主從切換和故障轉(zhuǎn)移,本文主要介紹了SpringBoot整合Redis的哨兵模式的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

在開(kāi)發(fā)中,Redis是一個(gè)非常流行和強(qiáng)大的緩存數(shù)據(jù)庫(kù)。為了保證高可用性和容錯(cuò)性,Redis提供了哨兵模式(Sentinel)來(lái)處理主從切換和故障轉(zhuǎn)移。 本篇技術(shù)博客將介紹如何在Spring Boot應(yīng)用中使用Redis的哨兵模式進(jìn)行高可用緩存服務(wù)的搭建。

準(zhǔn)備工作

在開(kāi)始之前,確保你已經(jīng)安裝和啟動(dòng)了Redis服務(wù)器,并按照Redis的哨兵模式配置了主節(jié)點(diǎn)和從節(jié)點(diǎn)。

添加依賴

pom.xml文件中添加Spring Data Redis和Jedis的依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

Redis配置

application.yaml文件中進(jìn)行Redis的配置,包括主服務(wù)器和哨兵節(jié)點(diǎn)的信息:

spring:
  redis:
    sentinel:
      master: mymaster  # 主節(jié)點(diǎn)名稱
      nodes: host1:port1,host2:port2,host3:port3  # 哨兵節(jié)點(diǎn)列表

創(chuàng)建Redis配置類

創(chuàng)建一個(gè)Redis的配置類,用于配置Redis連接工廠和緩存管理器:

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Value("${spring.redis.sentinel.master}")
    private String master;
    @Value("${spring.redis.sentinel.nodes}")
    private String sentinelNodes;
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration()
                .master(master);
        Set<String> nodes = new HashSet<>(Arrays.asList(sentinelNodes.split(",")));
        nodes.forEach(node -> {
            String[] parts = node.split(":");
            sentinelConfiguration.sentinel(parts[0], Integer.parseInt(parts[1]));
        });
        return new JedisConnectionFactory(sentinelConfiguration);
    }
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(10)); // 設(shè)置緩存過(guò)期時(shí)間為10分鐘
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(redisCacheConfiguration)
                .transactionAware()
                .build();
    }
}

在這個(gè)配置類中,我們首先通過(guò)讀取配置文件中的主節(jié)點(diǎn)名稱和哨兵節(jié)點(diǎn)列表來(lái)創(chuàng)建RedisSentinelConfiguration對(duì)象。然后,我們遍歷哨兵節(jié)點(diǎn)列表并將它們添加到配置中。 接下來(lái),我們使用JedisConnectionFactory來(lái)創(chuàng)建RedisConnectionFactory,并將之前創(chuàng)建的RedisSentinelConfiguration傳遞給它。 最后,我們創(chuàng)建了RedisCacheConfiguration并設(shè)置了一個(gè)常見(jiàn)的緩存過(guò)期時(shí)間,然后使用它來(lái)構(gòu)建RedisCacheManager。

使用Redis緩存

在Spring Boot的服務(wù)類或控制器中,我們可以使用@Cacheable@CachePut@CacheEvict等注解來(lái)實(shí)現(xiàn)緩存功能。這些注解可以應(yīng)用于方法上,以指定需要緩存的方法或操作。

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    @CachePut(value = "users", key = "#user.id")
    public User saveUser(User user) {
        return userRepository.save(user);
    }
    @CacheEvict(value = "users", key = "#id")
    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }
}

運(yùn)行應(yīng)用程序

現(xiàn)在,我們已經(jīng)完成了Spring Boot的Redis哨兵模式配置和使用Redis緩存的代碼編寫。 運(yùn)行應(yīng)用程序,并在需要使用緩存的地方使用上述的@Cacheable、@CachePut@CacheEvict注解,Spring Boot將自動(dòng)處理緩存,并通過(guò)Redis的哨兵模式提供高可用性和容錯(cuò)性。

當(dāng)結(jié)合實(shí)際應(yīng)用場(chǎng)景進(jìn)行Redis的哨兵模式配置時(shí),通常是為了實(shí)現(xiàn)高可用的緩存服務(wù)。下面給出一個(gè)示例代碼,假設(shè)我們有一個(gè)商品管理系統(tǒng),我們使用Redis緩存來(lái)存儲(chǔ)商品信息,并保證緩存的高可用性。 首先,我們需要在Spring Boot應(yīng)用中配置Redis的哨兵模式并使用Redis緩存。可以參考上面提到的配置和代碼。 然后,我們可以在商品服務(wù)類中使用Redis緩存來(lái)存儲(chǔ)和獲取商品信息。

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;
    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        // 先從緩存中獲取商品信息
        // 如果緩存中不存在,從數(shù)據(jù)庫(kù)中獲取,并將結(jié)果存入緩存
        return productRepository.findById(id).orElse(null);
    }
    @CachePut(value = "products", key = "#product.id")
    public Product saveProduct(Product product) {
        // 保存商品信息到數(shù)據(jù)庫(kù),并將結(jié)果存入緩存
        return productRepository.save(product);
    }
    @CacheEvict(value = "products", key = "#id")
    public void deleteProductById(Long id) {
        // 從數(shù)據(jù)庫(kù)中刪除商品信息,并從緩存中移除對(duì)應(yīng)的數(shù)據(jù)
        productRepository.deleteById(id);
    }
}

在上述代碼中,我們使用@Cacheable注解將getProductById方法標(biāo)記為可緩存的。當(dāng)調(diào)用該方法時(shí),Spring Boot會(huì)首先嘗試從緩存中獲取商品信息。如果緩存中存在對(duì)應(yīng)的數(shù)據(jù),則直接返回緩存中的數(shù)據(jù);如果緩存中不存在,則會(huì)從數(shù)據(jù)庫(kù)中獲取商品信息,并將結(jié)果存入緩存。 使用@CachePut注解將saveProduct方法標(biāo)記為緩存更新的操作。該方法用于保存或更新商品信息到數(shù)據(jù)庫(kù),并將最新的商品信息存入緩存。通過(guò)指定相同的緩存名稱和緩存鍵,可以覆蓋之前的緩存數(shù)據(jù)。 使用@CacheEvict注解將deleteProductById方法標(biāo)記為緩存失效的操作。該方法用于刪除數(shù)據(jù)庫(kù)中的商品信息,并從緩存中移除相應(yīng)的數(shù)據(jù)。 通過(guò)以上示例代碼,我們可以實(shí)現(xiàn)基于Redis的哨兵模式的高可用緩存服務(wù)。在生產(chǎn)環(huán)境中,可以部署多個(gè)Redis節(jié)點(diǎn),并使用哨兵模式來(lái)實(shí)現(xiàn)主從切換和故障轉(zhuǎn)移,以確保緩存服務(wù)的可用性和容錯(cuò)性。 請(qǐng)注意,上述示例代碼中的ProductRepository是一個(gè)假設(shè)的商品數(shù)據(jù)訪問(wèn)接口,具體的實(shí)現(xiàn)根據(jù)實(shí)際情況進(jìn)行編寫。另外,還需要在application.yaml中配置正確的Redis主節(jié)點(diǎn)和哨兵節(jié)點(diǎn)的信息。

Spring Boot中如何使用Redis的哨兵模式: 首先,確保已經(jīng)引入Spring Data Redis和Lettuce依賴。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
</dependency>

接下來(lái),在application.properties(或application.yml)中進(jìn)行配置,包括Redis的哨兵節(jié)點(diǎn)和密碼等信息:

# Redis配置
spring.redis.sentinel.master=my-master
spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
spring.redis.password=your-password

然后,使用@Configuration注解創(chuàng)建一個(gè)配置類,配置RedisTemplate和LettuceConnectionFactory:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class RedisConfig {
    @Bean
    public RedisSentinelConfiguration redisSentinelConfiguration() {
        RedisSentinelConfiguration configuration = new RedisSentinelConfiguration();
        configuration.master("my-master");
        configuration.sentinel("127.0.0.1", 26379);
        configuration.sentinel("127.0.0.1", 26380);
        configuration.sentinel("127.0.0.1", 26381);
        configuration.setPassword(RedisPassword.of("your-password"));
        return configuration;
    }
    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory(RedisSentinelConfiguration redisSentinelConfiguration) {
        return new LettuceConnectionFactory(redisSentinelConfiguration);
    }
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        return redisTemplate;
    }
}

最后,可以在業(yè)務(wù)邏輯中使用自動(dòng)注入的RedisTemplate來(lái)操作Redis數(shù)據(jù):

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }
    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

在上述示例代碼中,我們首先創(chuàng)建了一個(gè)RedisConfig配置類,通過(guò)@Bean注解配置了RedisSentinelConfigurationLettuceConnectionFactory。然后,我們創(chuàng)建了一個(gè)RedisTemplate并將LettuceConnectionFactory注入其中。最后,我們?cè)?strong>RedisService服務(wù)類中使用自動(dòng)注入的RedisTemplate來(lái)操作Redis數(shù)據(jù)。 請(qǐng)注意,上述示例代碼中的配置信息和Redis連接參數(shù)是示例,實(shí)際應(yīng)用中需要根據(jù)實(shí)際情況進(jìn)行配置和更改。

總結(jié)

通過(guò)本篇技術(shù)博客,我們學(xué)習(xí)了如何在Spring Boot應(yīng)用中使用Redis的哨兵模式進(jìn)行高可用性緩存服務(wù)的搭建。 要注意的是,為了實(shí)現(xiàn)真正的高可用性,需要在實(shí)際生產(chǎn)環(huán)境中正確配置Redis的主節(jié)點(diǎn)和哨兵節(jié)點(diǎn)。

到此這篇關(guān)于SpringBoot整合Redis的哨兵模式的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot Redis哨兵模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

邢台县| 和顺县| 油尖旺区| 金秀| 玉林市| 石门县| 河源市| 东乡族自治县| 九寨沟县| 崇义县| 开平市| 天门市| 柳江县| 内丘县| 安国市| 额尔古纳市| 囊谦县| 渝中区| 确山县| 珲春市| 孟津县| 克山县| 定襄县| 渭南市| 左贡县| 萝北县| 偏关县| 石狮市| 通辽市| 三门县| 江都市| 浮山县| 道孚县| 旺苍县| 西乌珠穆沁旗| 灵川县| 当阳市| 巴楚县| 普安县| 五大连池市| 雷山县|