大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
小编给大家分享一下Spring Boot Oauth2缓存UserDetails到Ehcache的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
成都创新互联公司是一家集网站建设,长沙县企业网站建设,长沙县品牌网站建设,网站定制,长沙县网站建设报价,网络营销,网络优化,长沙县网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
在Spring中有一个类CachingUserDetailsService实现了UserDetailsService接口,该类使用静态代理模式为UserDetailsService提供缓存功能。该类源码如下:
CachingUserDetailsService.java
public class CachingUserDetailsService implements UserDetailsService { private UserCache userCache = new NullUserCache(); private final UserDetailsService delegate; CachingUserDetailsService(UserDetailsService delegate) { this.delegate = delegate; } public UserCache getUserCache() { return this.userCache; } public void setUserCache(UserCache userCache) { this.userCache = userCache; } public UserDetails loadUserByUsername(String username) { UserDetails user = this.userCache.getUserFromCache(username); if (user == null) { user = this.delegate.loadUserByUsername(username); } Assert.notNull(user, "UserDetailsService " + this.delegate + " returned null for username " + username + ". This is an interface contract violation"); this.userCache.putUserInCache(user); return user; } }
CachingUserDetailsService默认的userCache属性值为new NullUserCache(),
该对象并未实现缓存。因为我打算使用EhCache来缓存UserDetails,所以需要使用Spring的EhCacheBasedUserCache类,该类是UserCache接口的实现类,主要是缓存操作。
缓存UserDetails到Ehcache的具体实现如下:
ehcache.xml
UserDetailsCacheConfig.java
@Slf4j @Configuration public class UserDetailsCacheConfig { @Autowired private CustomUserDetailsService customUserDetailsService; @Bean public UserCache userCache(){ try { EhCacheBasedUserCache userCache = new EhCacheBasedUserCache(); val cacheManager = CacheManager.getInstance(); val cache = cacheManager.getCache("userCache"); userCache.setCache(cache); return userCache; } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); } return null; } @Bean public UserDetailsService userDetailsService(){ Constructorctor = null; try { ctor = CachingUserDetailsService.class.getDeclaredConstructor(UserDetailsService.class); } catch (NoSuchMethodException e) { e.printStackTrace(); } Assert.notNull(ctor, "CachingUserDetailsService constructor is null"); ctor.setAccessible(true); CachingUserDetailsService cachingUserDetailsService = BeanUtils.instantiateClass(ctor, customUserDetailsService); cachingUserDetailsService.setUserCache(userCache()); return cachingUserDetailsService; } }
使用
@Autowired private UserDetailsService userDetailsService;
以上是“Spring Boot Oauth2缓存UserDetails到Ehcache的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!