Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
57 lines (46 loc) · 2.14 KB
/
Copy pathProgram.cs
File metadata and controls
57 lines (46 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using DemoRedisImplementation.DTO;
using StackExchange.Redis;
using System.Text.Json;
Console.WriteLine("🚀 Starting background job to fetch API every 5 seconds...");
string apiUrl = "https://pakgold.net/PGR/GoldRate"; // replace with your actual API
var redis = await ConnectionMultiplexer.ConnectAsync("RedisDb:6379");
IDatabase db = redis.GetDatabase();
var httpClient = new HttpClient();
while (true)
{
try
{
// 1. Call API
string json = await httpClient.GetStringAsync(apiUrl);
// 2. Deserialize into object
var marketRates = JsonSerializer.Deserialize<Commodities>(json);
// 3. Save full JSON into Redis
await db.StringSetAsync("MarketRates:Latest", json);
// 4. Save selected fields in a Redis Hash
await db.HashSetAsync("MarketRates:Hash", new HashEntry[]
{
new HashEntry("rawaBuy", marketRates.rawaBuy ?? ""),
new HashEntry("rawaSell", marketRates.rawaSell ?? ""),
new HashEntry("gold", marketRates.gold ?? ""),
new HashEntry("silver", marketRates.silver ?? ""),
new HashEntry("rateUpdateTime", marketRates.rateUpdateTime ?? "")
});
// 5. Read data back from Redis
string redisJson = await db.StringGetAsync("MarketRates:Latest");
string goldPrice = await db.HashGetAsync("MarketRates:Hash", "gold");
string silverPrice = await db.HashGetAsync("MarketRates:Hash", "silver");
string updateTime = await db.HashGetAsync("MarketRates:Hash", "rateUpdateTime");
Console.Clear();
Console.WriteLine("✅ Data Updated in Redis at: " + DateTime.Now);
Console.WriteLine("📦 Raw JSON (truncated): " + redisJson.Substring(0, 80) + "...");
Console.WriteLine("💰 Gold Price: " + goldPrice);
Console.WriteLine("🥈 Silver Price: " + silverPrice);
Console.WriteLine("⏰ Rate Update Time: " + updateTime);
}
catch (Exception ex)
{
Console.WriteLine("❌ Error fetching or saving data: " + ex.Message);
}
// Wait 5 seconds before next API call
await Task.Delay(1000);
}