使用HazelCast實現Spring Config Server配置

banq發表於2019-01-10

我們可以透過RabbitMQ將Spring Cloud Config伺服器的釋出配置設定用於MicroServices節點。這個解決方案的缺點:
  • Spring Cloud Config僅支援GIT repo以儲存配置
  • 當配置伺服器上的資料發生更改時,您需要手動將事件傳送到所有MicroServices節點

讓我們考慮另一個解決方案,如何刪除Spring Config Server並將配置資料的分發替換為具有HazelCast資料網格的節點。

配置Hazelcast
首先你需要為Hazelcast新增maven依賴:( hazelcast-spring,因為我們將使用Spring快取API和Hazelcast作為CACHE提供者)

<!-- https://mvnrepository.com/artifact/com.hazelcast/hazelcast-spring -->
<dependency>
    <groupId>com.hazelcast</groupId>
    <artifactId>hazelcast-spring</artifactId>
</dependency>

然後你需要配置Hazelcast,你有以下選擇:
  • 配置com.hazelcast.config.Config 或
  • 將hazelcast.xml配置放到classpath中。請參閱此文件 或
  • 如果您對hazelcast.xml名稱不滿意,請在檔案中設定-Dhazelcast.config變數

我的配置看起來:

@Bean
    public Config config() {
        Config config = new Config();

        config.setInstanceName("HazelcastService");
        config.setProperty("hazelcast.wait.seconds.before.join","10");

        config.getGroupConfig().setName("mygroup");
        config.getGroupConfig().setPassword("mypassword");

        config.getNetworkConfig().setPortAutoIncrement(true);
        config.getNetworkConfig().setPort(10555);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(true);

        SSLConfig sslConfig = new SSLConfig();
        sslConfig.setEnabled(false);
        config.getNetworkConfig().setSSLConfig(sslConfig);

        return config;
    }

  • 始終使用Hazelcast群組。不要干涉他人。檢查GroupConfig。
  • 始終使用埠增量。有時某些環境中的埠可能會被佔用。

如果您計劃將Hazelcast用作分散式快取,那麼您需要使用Hazelcast實現覆蓋cacheManager bean:

@Bean 
 HazelcastInstance hazelcastInstance(){ 
     return Hazelcast.newHazelcastInstance(config()); 
 } 

 @Bean 
 public CacheManager cacheManager(){ 
     return new HazelcastCacheManager(hazelcastInstance()); 
 }


帶有HazelCast快取的MicroServices

有以下Util服務:

package com.example.hazelcast;

import org.springframework.cache.annotation.Cacheable;

/**
 * Created by tomas.kloucek on 18.1.2017.
 */
public interface IHazelCastUtilService {
    @Cacheable("batchSize")
    int getBatchSize();
}

實現:

public class HazelCastUtilService implements IHazelCastUtilService {
    @Override
    public int getBatchSize() {
        try {
            System.out.println("Getting batch size from DAO...");
            TimeUnit.SECONDS.sleep(5);  // (1)
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 3;
    }
}


讓我們在以下的上下文MicroServices之間共享此服務:
Cities MicroService:

@RestController
public class CitiesController {
    final City[] cities = {
            new City("Brno", "Czech republic"),
            new City("Bern", "Switzeland"),
            new City("Berlin", "Germany"),
            new City("London", "England")
    };

    @Autowired
    private IHazelCastUtilService hazelCastUtilService;

    @RequestMapping("/cities")
    public Cities getCities() {
        final Cities result = new Cities();

        System.out.println("...Getting city from controller!!...");
        for (int i=0; i < hazelCastUtilService.getBatchSize();i++) {
            result.getCities().add(cities[i]);
        }

        return result;
    }
}

Persons MicroService:

@RestController
public class PersonsController {

    @Autowired
    private IHazelCastUtilService hazelCastUtilService;

    final Person[] persons = {
            new Person("Tomas", "Kloucek", "Programmer"),
            new Person("Linus", "Torvalds", "Linux"),
            new Person("Heinz", "Kabutz", "Java"),
            new Person("Jonathan", "Locke", "Wicket")
    };

    @RequestMapping("/persons")
    public Persons getPersons() {
        final Persons result = new Persons();

        System.out.println("...Getting person from controller!!...");
        for (int i=0; i < hazelCastUtilService.getBatchSize();i++) {
            result.getPersons().add(persons[i]);
        }

        return result;
    }
}


測試演示:

git clone https://bitbucket.org/tomask79/microservice-spring-hazelcast-caching.git
mvn clean install (in the root folder with pom.xml)
cd spring-microservice-registry
java -jar target/registry-0.0.1-SNAPSHOT.war
verify that NetFlix Eureka is running at http://localhost:9761

cd ..
cd spring-microservice-service1
java -jar target/service1-0.0.1-SNAPSHOT.war
verify at http://localhost:9761 that citiesService has been registered

cd ..
cd spring-microservice-service2
java -jar target/service2-0.0.1-SNAPSHOT.war
verify at http://localhost:9761 that personsService has been registered


為了確保兩個 MicroServices形成Hazelcast叢集,你需要看到類似的東西:

Members [2] {
        Member [10.130.48.104]:10555 this
        Member [10.130.48.104]:10556
}


訪問: http://localhost:8081/cities
看到下面輸出:

...Getting city from controller!!...
Getting batch size from DAO...


訪問http://localhost:8082/persons呼叫第二個微服務

...Getting person from controller!!...


因為之前已經由城市MicroService快取了“batchSize”設定。太可愛了!

相關文章