0
\$\begingroup\$

I want to improve performance for api. I design cache in dao layer. I use caffine cache. Basic code is:

CacheConfig.java

@Configuration
public class CacheConfig {

    @Autowired
    private AppDao appDao;

    @Bean(value = "appCache")
    public LoadingCache<String, App> appCache() {
        return Caffeine.newBuilder()
                .maximumSize(1000)
                .refreshAfterWrite(5, TimeUnit.MINUTES)
                .build(key -> appDao.getByKeyFromDB(key));
    }
}

AppDao.java

@Repository
public class AppDao {

    @Autowired
    @Qualifier(value = "appCache")
    private LoadingCache<String, App> appCache;

    @Autowired
    private AppMapper appMapper;

    // service call getByAppKey
    public App getByKey(String appKey) {
        App app = appCache.get(appKey);
        return app;
    }

    // appCache load data by getByKey
    public App getByKeyFromDB(String appKey) {
        LambdaQueryWrapper<App> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(App::getAppKey, appKey);
        return appMapper.selectOne(queryWrapper);
    }
}

I maybe divide getByKey and getByKeyFromDB to two file, but I have no idea. How do I divide getByKey and getByKeyFromDB to different modules?

\$\endgroup\$
0
\$\begingroup\$

Well if you want to distinct classes, you should create two classes:

class CahedDao {
  AppCache cache;
  getByKey(String)
} 

class DbDao {
  getByKeyFromDb(String)
}

Notes:

A. Codereview is to review working code, if you want to solve a problem you should better ask on stackexchange.

B. There are some issues in your code. Thanks to the DI and (bad) field injection you did not got them.

\$\endgroup\$
3
  • \$\begingroup\$ Thank you! What is the issues? \$\endgroup\$ May 11 at 10:57
  • \$\begingroup\$ You have a dependency loop, CacheConfig needs an AppDao to produce appCache and AppDao needs and appCache. \$\endgroup\$
    – gervais.b
    May 11 at 11:30
  • \$\begingroup\$ Thanks! I got it. \$\endgroup\$ May 11 at 12:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.