SlideShare una empresa de Scribd logo
1 de 13
Descargar para leer sin conexión
Document Locking
with Redis
Tom Corrigan
rostercloud.com
!

@thetommygnr

Melbourne PHP Users Group
November 2013
•

Cloud hosted SaaS product

•

Provide staff rostering primarily for hospitality companies

•

Focus on rostering staff to ad hoc events, not regular schedules

•

3 founders - I’m the IT guy
The problem
•

Multiple users editing an event at the same time

•

Resulting in:
•

Lost work

•

Unhappy customers
Solutions
•

Do nothing, let our customers figure it out
•

•

we might not have any customers

Store locks in our mysql database
•

edge cases are ugly
Redis - A better way

Redis is an open source, BSD licensed, advanced
key-value store. It is often referred to as a data
structure server since keys can contain strings,
hashes, lists, sets and sorted sets.
Redis…
•

Developed by Salvatore Sanfilippo (@antirez)

•

An in-memory data store with optional disk persistence

•

Clusters easily

•

Documentation is amazing!

•

Has myriad uses beyond what I am discussing today

•

Take a look, it will open your eyes to new solutions to age old problems
Using Redis
•

predis is the de facto standard library for PHP

•

can be further accelerated with a C extension

•

As a key value store Redis has a very simple
command set

•

We will be focusing on a handful of commands
today
How did we do it?

•

Create a set using the event id to form a key name

•

Populate the set with the ids of users who have
opened a read lock
Edit action
<?php	
class EventController extends Controller {	
!

	
	

public function editAction($event){	
	 //...	

!

	
	
	
	
	
	
	
	

	
	
	
	
	
	
	
	

//Check for an existing lock and redirect if one exists	
$redisKey = 'event_edit_'.$event->getId();	
$redis = $this->container->get('snc_redis.default');	
if ($redis->exists($redisKey)) {	
	 if (!$redis->sismember($redisKey, $this->getUser()->getId())){	
	 	 return $this->redirect($this->generateUrl(‘event_edit_conflict’, array('id' => $id)));	
	 }	
}	

	
	
	
	
	
	

	 //Create a lock for this user	
	 $redis->sadd($redisKey, $this->getUser()->getId());	
	 $redis->expire($redisKey, 120);	
}	
//...
Releasing a lock
public function updateAction(Request $request, $id)	
{	
	 //$businessLogic->doStuff($event)	
	 //etc...	
!

	 //Once the changes have been flushed to the database release the lock	
	 $redis = $this->container->get('snc_redis.default');	
	 $redis->srem('event_edit_'.$event->getId(), $this->getUser()->getId());	
!

	 //...	
}
Maintaining a lock while editing
Client Side
!

function pollEditLock() {	
	 	 $.get(	
	 	 	 '{{ path(‘event_edit_lock’,	
	 	 	 { 'id': entity.id })}}’,	
	 	 	 function(data) {	
	 	 	 	 	 	 //Do something	
	 	 	 }	
	 	 );	
}	
!
setInterval(pollEditLock, 30 * 1000);	
!

Server Side
!

<?php	
//...	
public function editLockAction(Event $event)	
{	
	 	 //...	
	 	 $redisKey = 'event_edit_'.$event->getId();	
	 	 $redis = $this->container->get('snc_redis.default');	
!
	 	 $redis->sadd($redisKey, $this->getUser()->getId());	
	 	 $redis->expire($redisKey, self::LOCK_TIME);	
!
	 	 return new JsonResponse(array('ok'));	
}	
//...
Sometimes users want to edit concurrently
public function editConflictAction(Request $request, $id)	
{	
	 //...	
!
	 $redisKey = 'event_edit_'.$entity->getId();	
	 $redis = $this->container->get('snc_redis.default');	
!
	 if ($request->query->get('force')) {	
	 	 $redis->sadd($redisKey, $this->getUser()->getId());	
	 	 $redis->expire($redisKey, self::LOCK_TIME);	
!
	 	 return $this->redirect($this->generateUrl('event_edit', array('id' => $id)));	
	 }	
	 	
	 $users = array();	
	 $client = $this->get('context.client');	
	 foreach ($redis->smembers($redisKey) as $userId){	
	 	 $users[] = $em->getRepository(‚ÀòRCRosterBundle:User‚ÀÙ)->find($userId);	
	 }	
!
	 //...	
}
Thankyou
Further Reading:
•

http://redis.io/

•

Slides available at https://speakerdeck.com/u/
tommygnr or from http://phpmelb.org

Más contenido relacionado

La actualidad más candente

MySQL Monitoring with Zabbix
MySQL Monitoring with ZabbixMySQL Monitoring with Zabbix
MySQL Monitoring with Zabbix
FromDual GmbH
 
Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. Redis
Tim Lossen
 

La actualidad más candente (20)

MySQL Monitoring with Zabbix
MySQL Monitoring with ZabbixMySQL Monitoring with Zabbix
MySQL Monitoring with Zabbix
 
Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. Redis
 
Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)
Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)
Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)
 
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
 
Open Source Logging and Metric Tools
Open Source Logging and Metric ToolsOpen Source Logging and Metric Tools
Open Source Logging and Metric Tools
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
 
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More! Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
 
Redis Developers Day 2014 - Redis Labs Talks
Redis Developers Day 2014 - Redis Labs TalksRedis Developers Day 2014 - Redis Labs Talks
Redis Developers Day 2014 - Redis Labs Talks
 
Redis Day Keynote Salvatore Sanfillipo Redis Labs
Redis Day Keynote Salvatore Sanfillipo Redis LabsRedis Day Keynote Salvatore Sanfillipo Redis Labs
Redis Day Keynote Salvatore Sanfillipo Redis Labs
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
 
Lessons Learned From Running Spark On Docker
Lessons Learned From Running Spark On DockerLessons Learned From Running Spark On Docker
Lessons Learned From Running Spark On Docker
 
Best practices for MySQL High Availability
Best practices for MySQL High AvailabilityBest practices for MySQL High Availability
Best practices for MySQL High Availability
 
Scaling Social Games
Scaling Social GamesScaling Social Games
Scaling Social Games
 
Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.
 
Mongrel2, a short introduction
Mongrel2, a short introductionMongrel2, a short introduction
Mongrel2, a short introduction
 
Redis at LINE
Redis at LINERedis at LINE
Redis at LINE
 
Freebsd, the unknown giant
Freebsd, the unknown giantFreebsd, the unknown giant
Freebsd, the unknown giant
 
Ansible for large scale deployment
Ansible for large scale deploymentAnsible for large scale deployment
Ansible for large scale deployment
 
Memcached
MemcachedMemcached
Memcached
 

Destacado

2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...
Brian LeDuc
 
Bảng báo giá hình tool
Bảng báo giá hình toolBảng báo giá hình tool
Bảng báo giá hình tool
sy_thanh2001
 
Project 1
Project 1Project 1
Project 1
e156160
 
Violéncia de génere
Violéncia de génereVioléncia de génere
Violéncia de génere
yatusaeh
 
Present rec 04_tor
Present rec 04_torPresent rec 04_tor
Present rec 04_tor
chibook
 
Tnu ariungerel
Tnu ariungerelTnu ariungerel
Tnu ariungerel
sayjargal
 
Танино хобби
Танино хоббиТанино хобби
Танино хобби
AkuJIa
 
[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with Python[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with Python
Jenny Liang
 

Destacado (20)

Redis in Practice
Redis in PracticeRedis in Practice
Redis in Practice
 
2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...
 
Egiptopp
EgiptoppEgiptopp
Egiptopp
 
Bảng báo giá hình tool
Bảng báo giá hình toolBảng báo giá hình tool
Bảng báo giá hình tool
 
Project 1
Project 1Project 1
Project 1
 
Violéncia de génere
Violéncia de génereVioléncia de génere
Violéncia de génere
 
המעצבים עבודות חוץ
המעצבים עבודות חוץהמעצבים עבודות חוץ
המעצבים עבודות חוץ
 
Eqf iserve jobs-descriptions
Eqf iserve jobs-descriptionsEqf iserve jobs-descriptions
Eqf iserve jobs-descriptions
 
Cfo act of 1990 driving the transformation of federal financial management
Cfo act of 1990 driving the transformation of federal financial managementCfo act of 1990 driving the transformation of federal financial management
Cfo act of 1990 driving the transformation of federal financial management
 
Present rec 04_tor
Present rec 04_torPresent rec 04_tor
Present rec 04_tor
 
Employment status key points
Employment status key pointsEmployment status key points
Employment status key points
 
Symfony - A baptism of fire
Symfony - A baptism of fireSymfony - A baptism of fire
Symfony - A baptism of fire
 
O señor mago
O señor magoO señor mago
O señor mago
 
Yb5500 pg
Yb5500  pgYb5500  pg
Yb5500 pg
 
Tnu ariungerel
Tnu ariungerelTnu ariungerel
Tnu ariungerel
 
Танино хобби
Танино хоббиТанино хобби
Танино хобби
 
good mood in bags
good mood in bagsgood mood in bags
good mood in bags
 
All about managing college environment dr. s. swapna kumar
All about managing college environment  dr. s. swapna kumarAll about managing college environment  dr. s. swapna kumar
All about managing college environment dr. s. swapna kumar
 
Presentación1
Presentación1Presentación1
Presentación1
 
[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with Python[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with Python
 

Similar a Document Locking with Redis in Symfony2

Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
MongoDB APAC
 

Similar a Document Locking with Redis in Symfony2 (20)

Redis At 6Wunderkinder
Redis At 6WunderkinderRedis At 6Wunderkinder
Redis At 6Wunderkinder
 
Craft CMS: Beyond the Small Business; Advanced tools and configurations
Craft CMS: Beyond the Small Business; Advanced tools and configurationsCraft CMS: Beyond the Small Business; Advanced tools and configurations
Craft CMS: Beyond the Small Business; Advanced tools and configurations
 
What is DDD and how could it help you
What is DDD and how could it help youWhat is DDD and how could it help you
What is DDD and how could it help you
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
Midgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applicationsMidgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applications
 
Drupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaDrupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp Bratislava
 
RedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis codeRedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis code
 
Drupal as a web framework
Drupal as a web frameworkDrupal as a web framework
Drupal as a web framework
 
Fatc
FatcFatc
Fatc
 
S3 & Glacier - The only backup solution you'll ever need
S3 & Glacier - The only backup solution you'll ever needS3 & Glacier - The only backup solution you'll ever need
S3 & Glacier - The only backup solution you'll ever need
 
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
 
Drupal 8 Render Cache
Drupal 8 Render CacheDrupal 8 Render Cache
Drupal 8 Render Cache
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
 
Redis the better NoSQL
Redis the better NoSQLRedis the better NoSQL
Redis the better NoSQL
 
Does my DIV look big in this?
Does my DIV look big in this?Does my DIV look big in this?
Does my DIV look big in this?
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Render Caching for Drupal 8
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8
 
Redispresentation apac2012
Redispresentation apac2012Redispresentation apac2012
Redispresentation apac2012
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Document Locking with Redis in Symfony2

  • 1. Document Locking with Redis Tom Corrigan rostercloud.com ! @thetommygnr Melbourne PHP Users Group November 2013
  • 2. • Cloud hosted SaaS product • Provide staff rostering primarily for hospitality companies • Focus on rostering staff to ad hoc events, not regular schedules • 3 founders - I’m the IT guy
  • 3. The problem • Multiple users editing an event at the same time • Resulting in: • Lost work • Unhappy customers
  • 4. Solutions • Do nothing, let our customers figure it out • • we might not have any customers Store locks in our mysql database • edge cases are ugly
  • 5. Redis - A better way Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.
  • 6. Redis… • Developed by Salvatore Sanfilippo (@antirez) • An in-memory data store with optional disk persistence • Clusters easily • Documentation is amazing! • Has myriad uses beyond what I am discussing today • Take a look, it will open your eyes to new solutions to age old problems
  • 7. Using Redis • predis is the de facto standard library for PHP • can be further accelerated with a C extension • As a key value store Redis has a very simple command set • We will be focusing on a handful of commands today
  • 8. How did we do it? • Create a set using the event id to form a key name • Populate the set with the ids of users who have opened a read lock
  • 9. Edit action <?php class EventController extends Controller { ! public function editAction($event){ //... ! //Check for an existing lock and redirect if one exists $redisKey = 'event_edit_'.$event->getId(); $redis = $this->container->get('snc_redis.default'); if ($redis->exists($redisKey)) { if (!$redis->sismember($redisKey, $this->getUser()->getId())){ return $this->redirect($this->generateUrl(‘event_edit_conflict’, array('id' => $id))); } } //Create a lock for this user $redis->sadd($redisKey, $this->getUser()->getId()); $redis->expire($redisKey, 120); } //...
  • 10. Releasing a lock public function updateAction(Request $request, $id) { //$businessLogic->doStuff($event) //etc... ! //Once the changes have been flushed to the database release the lock $redis = $this->container->get('snc_redis.default'); $redis->srem('event_edit_'.$event->getId(), $this->getUser()->getId()); ! //... }
  • 11. Maintaining a lock while editing Client Side ! function pollEditLock() { $.get( '{{ path(‘event_edit_lock’, { 'id': entity.id })}}’, function(data) { //Do something } ); } ! setInterval(pollEditLock, 30 * 1000); ! Server Side ! <?php //... public function editLockAction(Event $event) { //... $redisKey = 'event_edit_'.$event->getId(); $redis = $this->container->get('snc_redis.default'); ! $redis->sadd($redisKey, $this->getUser()->getId()); $redis->expire($redisKey, self::LOCK_TIME); ! return new JsonResponse(array('ok')); } //...
  • 12. Sometimes users want to edit concurrently public function editConflictAction(Request $request, $id) { //... ! $redisKey = 'event_edit_'.$entity->getId(); $redis = $this->container->get('snc_redis.default'); ! if ($request->query->get('force')) { $redis->sadd($redisKey, $this->getUser()->getId()); $redis->expire($redisKey, self::LOCK_TIME); ! return $this->redirect($this->generateUrl('event_edit', array('id' => $id))); } $users = array(); $client = $this->get('context.client'); foreach ($redis->smembers($redisKey) as $userId){ $users[] = $em->getRepository(‚ÀòRCRosterBundle:User‚ÀÙ)->find($userId); } ! //... }
  • 13. Thankyou Further Reading: • http://redis.io/ • Slides available at https://speakerdeck.com/u/ tommygnr or from http://phpmelb.org