Implementing Model-level caching

前端 未结 8 1507
孤城傲影
孤城傲影 2021-01-31 00:28

I was posting some comments in a related question about MVC caching and some questions about actual implementation came up. How does one implement a Model-level cache that works

8条回答
  •  梦如初夏
    2021-01-31 01:00

    Your post only makes any sense if the model is a trivial ORM. And there are lots of reasons why that's a bad thing. Try thinking about the model as if it were a web service.

    Caching is the responsiblity of the model.

    How would you uniquely identify a query from another query (or more accurately, a result set from another result set)? What about if you're using prepared statements, with only the parameters changing according to user input?

    But the inputs to the model uniquely define its output.

    If you're using the same model to retrieve the contents of a shopping basket and to run a search on your product catalog then there's something wrong with your code.

    Even in the case of the shopping basket, there may be merit in caching data with a TTL of less than the time taken to process a transaction which would change its contents, in the case of the catalog search, caching the list of matching products for a few hours will probably have no measurable impact on sales, but trade-off well in reducing database load.

    The fact that you are using a trivial ORM out of the box does not exclude you from wrapping it in your own code.

    Wouldn't the Model have to be astronomically smart, and/or store statistics

    No. You make the determination on whether to cache, and if you can't ensure that the cache is consistent then enforce a TTL based on the type of request.

    As a general rule of thumb, you should be able to predict appropriate TTLs based on the SELECT query before binding any variables and this needs to be implemented at design time - but obviously the results should be indexed based on the query after binding.

    Should I implement the caching individually in the Model classes that require it, or should it be part of the ORM layer?

    For preference I would implement this as a decorator on the model class - that way you can easily port it to models which implement a factory rather than trivial ORM.

    C.

提交回复
热议问题