Problem statement

Our sample is an application excerpt from a distributed prime factorization engine that needs to calculate fibonacci numbers but would
like to reuse expensively calculated results since fibonacci numbers since the computations of such numbers are CPU intensive.

To share/memoize results amongst our distributed applications, we’ll use Memcache.
However, to examine our changes in a distributed systems deployment with numerous microservices, it is useful to have tracing and metrics to verify our optimizations
and inspect the state of the system.

Please run your Memcached server, for this example we’ll run it locally on port 11211.

#!/usr/bin/env pythonimporttimefromocpymemcache.clientimportOCPyMemcacheClientdefnum_as_str(num):return'%d'%numdefmain():# Create the Memcache clientmc=OCPyMemcacheClient(("localhost",11211,))do_work(mc)time.sleep(5)defdo_work(mc):values=[30,33,]forvalueinvalues:foriinrange(0,2):nf=nth_fibonacci(mc,value)print("Fibonacci %d ==> %d"%(value,nf))# Afterwards, clean up to ensure repeatability of the testmc.delete(num_as_str(value))deffib(n):ifn<=0:return1returnfib(n-2)+fib(n-1)defnth_fibonacci(mc,n):# Firstly check if we've cached itnum_str=num_as_str(n)res=mc.get(num_str)ifresisnotNone:try:# Try parsing it as a floatreturnint(res)exceptValueErrorase:# Failed to parse it_=0# Otherwise this was a cache miss, so go onvalue=fib(n)as_str=num_as_str(value)# Now cache it for a cache hit later onmc.set(num_str,as_str)returnvalueif__name__=='__main__':main()