Skip to content

Commit dedb3ac

Browse files
committed
Add initial examples.
1 parent 5b21f1c commit dedb3ac

File tree

5 files changed

+187
-8
lines changed

5 files changed

+187
-8
lines changed

examples/basic/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Basic Examples
2+
3+
These examples demonstrate basic operations against a NamedMap.
4+
5+
To run:
6+
```bash
7+
python3 <example-name>
8+
```

examples/basic/crud.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Copyright (c) 2023, Oracle and/or its affiliates.
2+
# Licensed under the Universal Permissive License v 1.0 as shown at
3+
# https://oss.oracle.com/licenses/upl.
4+
5+
import asyncio
6+
7+
from coherence import NamedMap, Session
8+
9+
10+
async def do_run() -> None:
11+
"""
12+
Demonstrates basic CRUD operations against a NamedMap using
13+
`int` keys and `str` values.
14+
15+
:return: None
16+
"""
17+
session: Session = Session()
18+
try:
19+
namedMap: NamedMap[int, str] = await session.get_map("my-map")
20+
21+
print("Put key 1; value one")
22+
await namedMap.put(1, "one")
23+
24+
print("Value for key 1 is : " + str(await namedMap.get(1)))
25+
26+
print("NamedMap size is : " + str(await namedMap.size()))
27+
28+
print("Updating value of key 1 to ONE from " + await namedMap.put(1, "ONE"))
29+
30+
print("Value for key 1 is : " + str(await namedMap.get(1)))
31+
32+
print("Removing key 1, current value : " + await namedMap.remove(1))
33+
34+
print("NamedMap size is : " + str(await namedMap.size()))
35+
finally:
36+
await session.close()
37+
38+
39+
asyncio.run(do_run())

examples/basic/python_object_keys.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import asyncio
2+
from dataclasses import dataclass
3+
4+
from coherence import NamedMap, Processors, Session
5+
6+
7+
@dataclass
8+
class AccountKey:
9+
accountId: int
10+
accountType: str
11+
12+
13+
@dataclass
14+
class Account:
15+
accountId: int
16+
accountType: str
17+
name: str
18+
balance: float
19+
20+
21+
async def do_run() -> None:
22+
"""
23+
Demonstrates basic CRUD operations against a NamedMap using
24+
`AccountKey` keys with `Account` values.
25+
26+
:return: None
27+
"""
28+
session: Session = Session()
29+
try:
30+
namedMap: NamedMap[AccountKey, Account] = await session.get_map("accounts")
31+
32+
await namedMap.clear()
33+
34+
new_account_key: AccountKey = AccountKey(100, "savings")
35+
new_account: Account = Account(new_account_key.accountId, new_account_key.accountType, "John Doe", 100000.00)
36+
37+
print(f"Add new account {new_account} with key {new_account_key}")
38+
await namedMap.put(new_account_key, new_account)
39+
40+
print("NamedMap size is : " + str(await namedMap.size()))
41+
42+
print("Account from get() : " + str(await namedMap.get(new_account_key)))
43+
44+
print("Update account balance using processor ...")
45+
await namedMap.invoke(new_account_key, Processors.update("balance", new_account.balance + 1000))
46+
47+
print("Updated account is : " + str(await namedMap.get(new_account_key)))
48+
49+
await namedMap.remove(new_account_key)
50+
51+
print("NamedMap size is : " + str(await namedMap.size()))
52+
finally:
53+
await session.close()
54+
55+
56+
asyncio.run(do_run())
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import asyncio
2+
from dataclasses import dataclass
3+
4+
from coherence import NamedMap, Processors, Session
5+
6+
7+
@dataclass
8+
class Person:
9+
"""
10+
A simple class representing a person.
11+
"""
12+
13+
id: int
14+
name: str
15+
age: int
16+
17+
18+
async def do_run() -> None:
19+
"""
20+
Demonstrates basic CRUD operations against a NamedMap using
21+
`int` keys and a custom python type, Person, as the value.
22+
23+
:return: None
24+
"""
25+
session: Session = Session()
26+
try:
27+
namedMap: NamedMap[int, Person] = await session.get_map("people")
28+
29+
await namedMap.clear()
30+
31+
person: Person = Person(1, "Bilbo", 111)
32+
print("Add new person : " + str(person))
33+
await namedMap.put(person.id, person)
34+
35+
print("NamedMap size is : " + str(await namedMap.size()))
36+
37+
print("Person from get() : " + str(await namedMap.get(person.id)))
38+
39+
print("Update person using processor ...")
40+
await namedMap.invoke(person.id, Processors.update("age", 112))
41+
42+
print("Updated person is : " + str(await namedMap.get(person.id)))
43+
44+
await namedMap.remove(person.id)
45+
46+
print("NamedMap size is : " + str(await namedMap.size()))
47+
finally:
48+
await session.close()
49+
50+
51+
asyncio.run(do_run())

src/coherence/client.py

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import asyncio
99
import os
1010
from asyncio import Task
11+
from threading import Lock
1112
from typing import (
1213
Any,
1314
AsyncIterator,
@@ -1037,6 +1038,7 @@ def __init__(self, session_options: Optional[Options] = None):
10371038
"""
10381039
self._closed: bool = False
10391040
self._caches: dict[str, NamedCache[Any, Any]] = dict()
1041+
self._lock: Lock = Lock()
10401042
if session_options is not None:
10411043
self._session_options = session_options
10421044
else:
@@ -1159,14 +1161,37 @@ async def get_cache(self, name: str, ser_format: str = DEFAULT_FORMAT) -> "Named
11591161
:return: Returns a :func:`coherence.client.NamedCache` for the specified cache name.
11601162
"""
11611163
serializer = SerializerRegistry.serializer(ser_format)
1162-
c = self._caches.get(name)
1163-
if c is None:
1164-
c = NamedCacheClient(name, self, serializer)
1165-
# initialize the event stream now to ensure lifecycle listeners will work as expected
1166-
await c._events_manager._ensure_stream()
1167-
self._setup_event_handlers(c)
1168-
self._caches.update({name: c})
1169-
return c
1164+
with self._lock:
1165+
c = self._caches.get(name)
1166+
if c is None:
1167+
c = NamedCacheClient(name, self, serializer)
1168+
# initialize the event stream now to ensure lifecycle listeners will work as expected
1169+
await c._events_manager._ensure_stream()
1170+
self._setup_event_handlers(c)
1171+
self._caches.update({name: c})
1172+
return c
1173+
1174+
# noinspection PyProtectedMember
1175+
@_pre_call_session
1176+
async def get_map(self, name: str, ser_format: str = DEFAULT_FORMAT) -> "NamedMap[K, V]":
1177+
"""
1178+
Returns a :func:`coherence.client.NameMap` for the specified cache name.
1179+
1180+
:param name: the map name
1181+
:param ser_format: the serialization format for keys and values stored within the cache
1182+
1183+
:return: Returns a :func:`coherence.client.NamedMap` for the specified cache name.
1184+
"""
1185+
serializer = SerializerRegistry.serializer(ser_format)
1186+
with self._lock:
1187+
c = self._caches.get(name)
1188+
if c is None:
1189+
c = NamedCacheClient(name, self, serializer)
1190+
# initialize the event stream now to ensure lifecycle listeners will work as expected
1191+
await c._events_manager._ensure_stream()
1192+
self._setup_event_handlers(c)
1193+
self._caches.update({name: c})
1194+
return c
11701195

11711196
# noinspection PyUnresolvedReferences
11721197
async def close(self) -> None:

0 commit comments

Comments
 (0)