【发布时间】:2017-11-20 06:53:07
【问题描述】:
我的项目有两个应用程序。一个是 API 模块,另一个是后端管理。他们使用相同的数据库,我使用 spring boot 1.3.7 和数据 jpa 1.9.4 和 hibernate 4.3.11 。API 是用户登录和处理业务的 http restful 端点。管理系统是维护系统的数据。这是我通过管理 UI 插入新数据时出现的问题,API 模块直到大约 5 分钟后才能立即检索数据。一种情况是当我在后端添加新用户时,在 API 中,方法 findByUsername 不会获取我刚刚添加的用户名。有什么想法可以解决这个问题吗?任何建议将不胜感激!
API
package com.brahalla.Cerberus.service.impl;
import com.brahalla.Cerberus.domain.entity.User;
import com.brahalla.Cerberus.model.factory.CerberusUserFactory;
import com.brahalla.Cerberus.model.security.CerberusUser;
import com.brahalla.Cerberus.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
/**
* API :findByUsername
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
} else {
return CerberusUserFactory.create(user);
}
}
}
后端管理
package com.brahalla.Cerberus.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.brahalla.Cerberus.domain.entity.User;
import com.brahalla.Cerberus.repository.UserRepository;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserRepository userRepository;
/**
* Backend add new user
*
* @param user
* @return
*/
@RequestMapping(method = RequestMethod.POST)
public String create(User user) {
user.setId(null);
userRepository.save(user);
return "redirect:/";
}
}
用户存储库
package com.brahalla.Cerberus.repository;
import com.brahalla.Cerberus.domain.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByUsername(String username);
}
【问题讨论】:
-
5 分钟时间太长了,当您在同一个数据库上进行 R/W 操作时,即使我们使用主/从拓扑、复制,仍然 5 分钟看起来太多了时间。请放一些代码来进一步分析,您能否向我们展示您正在从数据库中写入和读取的类/包导入的示例代码,仅以用户为例。
-
禁用 L1 缓存是一个愚蠢的想法,即使假设您的 JPA 提供程序允许这样做
-
我已经添加了上面的示例代码。这两个示例代码来自两个模块,API 和 Backend。这意味着两个 .war 将被打包。但是 R/W 数据库是一样的。**我认为我的问题的真正问题是当我在 jpa 之外插入/更新数据时如何检索新数据,例如 Navicat Client*
-
请看上面@AnkurSinghal
-
@phxism 请添加
UserRepository
标签: hibernate jpa spring-boot spring-data-jpa