Невозможно работать с регионами, определенными в контексте Spring для встроенного сервера кэширования Apache Geode - PullRequest
0 голосов
/ 11 мая 2018

Я создал репозиторий SpringbootGeodeExample для демонстрационных целей.

Запустил локатор в Gfsh и сервер кэширования, встроенный в приложение Spring Boot, с некоторыми регионами, определенными в контексте Spring для сервера встроенного кэша.Теперь я могу перечислить регион, но не смог запросить и уничтожить регион, выполнить «описать» регион показывает, что «Члены хостинга» пустые.

gfsh>describe region --name=Region1
..........................................................
Name            : Region1
Data Policy     : partition
Hosting Members :

gfsh>query --query="select * from /Region1"
Result  : false
Message : Cannot find regions <[/Region1]> in any of the members

gfsh>destroy region --name=Region1
Could not find a Region with Region path "Region1" in this Geode cluster. If region was recently created, please wait for at least jmx-manager-update-rate milliseconds to allow the associated Management resources to be federated.

Я могу сделать выше для регионов, созданных в Gfsh, как я могувыполнять те же операции CRUD для регионов, созданных в контексте Spring?

Я пытался добавить --enable-cluster-configuration = true и use-cluster-configuration = "true" в локаторе и сервере кэша, но все еще не работает.

Подробнее: Конфигурация приложения сервера кэша:

@SpringBootApplication
@CacheServerApplication
@EnableCacheServer(autoStartup = true, port = 41414)
@ImportResource("classpath:spring-cache-context-cluster-side.xml")
public class CacheServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheServerApplication.class, args);
    }
}

Определение региона в контексте весны:

<gfe:partitioned-region id="Region1" copies="1">
        <gfe:eviction type="MEMORY_SIZE" threshold="512" action="LOCAL_DESTROY"/>
</gfe:partitioned-region>

Обновление в соответствии с комментарием от Джона:

Обновление 1:

Участники списка показывают, что имя сервера кэша пусто, является ли это основной причиной?

gfsh>list members
  Name   | Id
-------- | -----------------------------------------------
locator2 | 192.168.1.2(locator2:1396:locator)<ec><v0>:1024
         | 192.168.1.2(6032)<v3>:1025

Я пытался изменить аннотации на:

@SpringBootApplication
@CacheServerApplication(name = "MyServer", locators="localhost[10334]", autoStartup = true, port = 41415)
@EnableCacheServer(name = "MyServer", autoStartup = true, port = 41414)
@ImportResource("classpath:spring-cache-context-cluster-side.xml")

но безуспешно, имя сервера пусто.

Обновление 2:

Я использую spring-data-geode 2.0.6.RELEASE geode-core 1.2.1 Мои зависимости maven:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.RC1</spring-cloud.version>
        <spring-cloud-services.version>1.5.0.RELEASE</spring-cloud-services.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <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>
        <dependency>
                <groupId>io.pivotal.spring.cloud</groupId>
                <artifactId>spring-cloud-services-dependencies</artifactId>
                <version>${spring-cloud-services.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

   <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-geode</artifactId>
        </dependency>

Обновление 3:

spring-cache-context-cluster-side.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:gfe="http://www.springframework.org/schema/geode"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/geode http://www.springframework.org/schema/gemfire/spring-geode.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 


    <bean id="pdxSerializer" class="org.apache.geode.pdx.ReflectionBasedAutoSerializer">
        <constructor-arg value="com.WMModel.model.*"/>
    </bean>

    <util:properties id="gemfireProperties">
        <prop key="locators">${geode.cache.server.locators}</prop>
        <prop key="mcast-port">0</prop>
    </util:properties>

    <gfe:cache
        properties-ref="gemfireProperties"
        id="gemfireCache"
        use-cluster-configuration="true"
        pdx-serializer-ref="pdxSerializer" 
        copy-on-read="false" 
        critical-heap-percentage="85" 
        eviction-heap-percentage="80">
       <gfe:transaction-listener> 
            <bean class="com.WMCacheServer.db.op.WmTransactionListener"/>
        </gfe:transaction-listener>
        <gfe:transaction-writer> 
            <bean class="com.WMCacheServer.db.op.WmTransactionWriter"/>
        </gfe:transaction-writer>   
        <gfe:dynamic-region-factory/>     
    </gfe:cache>

    <!-- configure the cache and set the port to 0 for it picks the first available port -->
    <gfe:cache-server 
        id="advanced-config"
        port="${geode.cache.server.port}"
        auto-startup="true"
        cache-ref="gemfireCache" />
    <context:property-placeholder location="classpath:cache-server.properties"/>


    <gfe:partitioned-region id="Region1" copies="1">
        <gfe:eviction type="MEMORY_SIZE" threshold="512" action="LOCAL_DESTROY"/>
    </gfe:partitioned-region>
</beans>

cache-server.properties:

### For complete options list: http://gemfire.docs.gopivotal.com/index.html?q=/reference/topics/gemfire_properties.html ###

### Logging ###
log-level=config

### Turn Off Multi Cast ###
mcast-port=0

### Turn on Statistics ###
statistic-archive-file=stats.gfs
statistic-sample-rate=1000
statistic-sampling-enabled=true

enable-network-partition-detection=false

##Conserve Sockets##
conserve-sockets=false
geode.cache.server.port=40434
#geode.cache.server.locators=peer2.com[10334],localhost[10334]
geode.cache.server.locators=localhost[10334]

Ответы [ 2 ]

0 голосов
/ 12 мая 2018

ОК, решено путем изменения зависимостей Maven.Спасибо Джон!Похоже, существует конфликт между spring-boot и spring-data-geode.Надеюсь, что geode-spring-boot-starter будет выпущен в ближайшее время.Моя обновленная зависимость:

<dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-geode</artifactId>
        <version>2.0.1.RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>          
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.7</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.shell</groupId>
      <artifactId>spring-shell</artifactId>
      <version>1.2.0.RELEASE</version>
       <exclusions>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
0 голосов
/ 11 мая 2018

Какие версии Apache Geode и Spring Data Geode вы используете?

Каков выход list members?

Судя по классу CacheServerApplication, ваш Spring (Geode данных) сконфигурирован и загружен Apache Geode сервер не подключается к / Locator. Кроме того, вы можете упростить настройку до этого ...

@SpringBootApplication
@CacheServerApplication(name = "MyServer", locators="localhost[10334]"
    autoStartup = true, port = 41414)
@ImportResource("classpath:spring-cache-context-cluster-side.xml")
public class CacheServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheServerApplication.class, args);
    }
}

Обратите внимание, что я добавил атрибут name к аннотации @CacheServerApplication, чтобы явно указать имя сервера. Это рекомендуется, поскольку имя члена должно быть уникальным в кластере, и если вы запускаете более одного сервера, используя один и тот же класс, имя по умолчанию (т.е. "SpringBasedCacheServerApplication") будет конфликтовать. Конечно, он также может конфликтовать с номером порта CacheServer, поскольку он жестко задан (то есть "41414"). Вы можете использовать динамическую конфигурацию с Configurers или Properties .

Кроме того, для атрибута locators установлено значение "localhost [10334]". Вам следует изменить хост и порт локатора (в формате строки host [port]) на хост и порт, на котором работает локатор / прослушивает соединения член / клиент.

У меня есть пример настроенного и загруженного Spring-сервера Pivotal GemFire ​​в моем репозитории Spring Boot GemFire ​​Пример . Я только что обновил этот пример до Spring Boot 2.0.2.RELEASE . Это включает Spring Data Kay-SR7 , который включает в себя Spring Data GemFire ​​ 2.0.7.RELEASE , который основан на Pivotal GemFire ​​ 9.1.1 .

Кроме того, этот пример изначально был основан на конфигурации Java, поскольку в нем используется новая Модель конфигурации на основе аннотаций в SDG. Поэтому в действительности нет смысла использовать XML, так как вы можете определять регион в JavaConfig .

Но, неважно. Мы можем немного изменить этот пример, чтобы он также основывался на XML.

ПРИМЕЧАНИЕ. Сервер в моем примере репозитория также является автономным, автономным сервером / кластером с собственной конфигурацией Locator и Manager. Однако я только что разделил эту конфигурацию на вложенный статический @Configuration класс , который активируется с помощью Spring Profile (то есть, установив свойство System -Dspring.profiles.active=locator-manager). Когда этот профиль включен, вам не нужно запускать автономный локатор, хотя вы все еще можете. Вы просто должны помнить о конфликтах портов и т. Д. В любом случае ...

Я только что добавил ветку xml-config в мой репозиторий.

Затем я настроил регион " Factorials ", используя пространство имен SDG XML, импортировал его и настроил конечную точку локатора подключиться к внешне запущенному локатору.

Затем я запустил Gfsh , запустил локатор и приступил к запуску SpringBootGemFireServerExample класса ...

$ echo $GEMFIRE
/Users/jblum/pivdev/pivotal-gemfire-9.1.1
$ 
$ gfsh
    _________________________     __
   / _____/ ______/ ______/ /____/ /
  / /  __/ /___  /_____  / _____  / 
 / /__/ / ____/  _____/ / /    / /  
/______/_/      /______/_/    /_/    9.1.1

Monitor and Manage Pivotal GemFire

gfsh>list members
Command 'list members' was found but is not currently available (type 'help' then ENTER to learn about this command)
gfsh>
gfsh>start locator --name=LocatorOne --log-level=config --J=-Dgemfire.http-service-port=0
Starting a Geode Locator in /Users/jblum/pivdev/lab/LocatorOne...
...
Locator in /Users/jblum/pivdev/lab/LocatorOne on 10.0.0.121[10334] as LocatorOne is currently online.
Process ID: 33659
Uptime: 3 seconds
Geode Version: 9.1.1
Java Version: 1.8.0_152
Log File: /Users/jblum/pivdev/lab/LocatorOne/LocatorOne.log
JVM Arguments: -Dgemfire.log-level=config -Dgemfire.enable-cluster-configuration=true -Dgemfire.load-cluster-configuration-from-dir=false -Dgemfire.http-service-port=0 -Dgemfire.launcher.registerSignalHandlers=true -Djava.awt.headless=true -Dsun.rmi.dgc.server.gcInterval=9223372036854775806
Class-Path: /Users/jblum/pivdev/pivotal-gemfire-9.1.1/lib/geode-core-9.1.1.jar:/Users/jblum/pivdev/pivotal-gemfire-9.1.1/lib/geode-dependencies.jar

Successfully connected to: JMX Manager [host=10.0.0.121, port=1099]

Cluster configuration service is up and running.


gfsh>list members
   Name    | Id
---------- | -------------------------------------------------
LocatorOne | 10.0.0.121(LocatorOne:33659:locator)<ec><v0>:1024

Теперь я продолжаю свой класс SpringBootGemFireServerExample в моей среде IDE. Имейте в виду, у меня не включен профиль Spring "locator-manager" (то есть -Dspring.profiles.active= (пусто)). Я не хочу запускать встроенный локатор / менеджер, так как я хочу подключиться к запущенному Gfsh локатору, поэтому это ...

@CacheServerApplication(... locators="localhost[10334]")

После того, как я запустил свой сервер из среды IDE, подключившись к этому локатору ...

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.2.RELEASE)

[info 2018/05/11 11:53:36.883 PDT <main> tid=0x1] 
---------------------------------------------------------------------------

  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with this
  work for additional information regarding copyright ownership.

  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with the
  License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
  License for the specific language governing permissions and limitations
  under the License.

---------------------------------------------------------------------------
Build-Date: 2017-09-08 19:39:04 +0000
Build-Id: root 51
Build-Java-Version: 1.8.0_144
Build-Platform: Linux 4.4.0-62-generic amd64
GemFire-Source-Date: 2017-09-01 21:01:32 +0000
GemFire-Source-Repository: support/9.1
GemFire-Source-Revision: ac20a06062204a8f6ba2acaaf2c7dbc1a3d0cfe0
Product-Name: Pivotal GemFire
Product-Version: 9.1.1
Source-Date: 2017-09-08 19:07:34 +0000
Source-Repository: support/9.1
Source-Revision: e756828d0e631cec47f3d027555c022f0fb0e5cc
Native version: native code unavailable
Running on: /10.0.0.121, 8 cpu(s), x86_64 Mac OS X 10.10.5 
Communications version: 65
Process ID: 33670
...
..
.
[info 2018/05/11 11:53:38.454 PDT <main> tid=0x1] CacheServer Configuration:   port=40404 max-connections=800 max-threads=0 notify-by-subscription=true socket-buffer-size=32768 maximum-time-between-pings=60000 maximum-message-count=230000 message-time-to-live=180 eviction-policy=none capacity=1 overflow directory=. groups=[] loadProbe=ConnectionCountProbe loadPollInterval=5000 tcpNoDelay=true

Я вижу, что сервер присоединился к кластеру, определенному локатором в Gfsh ...

gfsh>list members
         Name           | Id
----------------------- | --------------------------------------------------
LocatorOne              | 10.0.0.121(LocatorOne:33659:locator)<ec><v0>:1024
SpringBootGemFireServer | 10.0.0.121(SpringBootGemFireServer:33670)<v1>:1025

gfsh>describe member --name=SpringBootGemFireServer
Name        : SpringBootGemFireServer
Id          : 10.0.0.121(SpringBootGemFireServer:33670)<v1>:1025
Host        : 10.0.0.121
Regions     : Factorials
PID         : 33670
Groups      : 
Used Heap   : 52M
Max Heap    : 3641M
Working Dir : /Users/jblum/pivdev/spring-data-examples-workspace/spring-boot-gemfire-server-example/build
Log file    : /Users/jblum/pivdev/spring-data-examples-workspace/spring-boot-gemfire-server-example/build
Locators    : localhost[10334]

Cache Server Information
Server Bind              : 
Server Port              : 40404
Running                  : true
Client Connections       : 0

Вы также можете видеть, что область PARTITION "Factorials" размещается на сервере SpringBootGemFireServer, что также видно из ...

gfsh>list regions
List of regions
---------------
Factorials

gfsh>describe region --name

required --name: Name/Path of the region to be described.; no default value
gfsh>describe region --name=/Factorials
..........................................................
Name            : Factorials
Data Policy     : partition
Hosting Members : SpringBootGemFireServer

Non-Default Attributes Shared By Hosting Members  

 Type  |    Name     | Value
------ | ----------- | ---------
Region | size        | 0
       | data-policy | PARTITION

Далее я получаю доступ к значению с помощью цифровой клавиши.

ПРИМЕЧАНИЕ. В этом примере присоединяет a "Факториал", основанный на вычислениях CacheLoader, к региону "Факториалы" PARTITION.

gfsh>get --region=/Factorials --key=3 --key-class=java.lang.Long
Result      : true
Key Class   : java.lang.Long
Key         : 3
Value Class : java.lang.Long
Value       : 6


gfsh>get --region=/Factorials --key=5 --key-class=java.lang.Long
Result      : true
Key Class   : java.lang.Long
Key         : 5
Value Class : java.lang.Long
Value       : 120

И, наконец, я могу запросить значения в области PARTITION "Factorials", вот так ...

gfsh>query --query="SELECT * FROM /Factorials"
Result : true
Limit  : 100
Rows   : 2

Result
------
6
120

Когда вы "describe" Регион, вы можете видеть, что он был изменен (см. "Размер").

gfsh>describe region --name=/Factorials
..........................................................
Name            : Factorials
Data Policy     : partition
Hosting Members : SpringBootGemFireServer

Non-Default Attributes Shared By Hosting Members  

 Type  |    Name     | Value
------ | ----------- | ---------
Region | size        | 2
       | data-policy | PARTITION

В любом случае, все хорошо.Надеюсь, это поможет!

-Джон

...