首页 文章 精选 留言 我的

精选列表

搜索[X3D技术],共10000篇文章
优秀的个人博客,低调大师

Spring 框架文档之核心技术—— AOP

AOP AOP 提供一种新的思考程序结构的方法来补充 OOP。OOP 中模块的关键是类,而 AOP 中模块的关键是切面。切面支持跨多个类型和对象的模块化(如事务管理)。 AOP 概念 切面 —— 在切入点进行通知操作的过程(包含通知和切人点的类 @Aspect) 连接点 —— 所有可能被织入通知的候选点(具体业务逻辑方法) 切入点 —— 满足匹配规则的连接点(@Pointcut) 目标对象 —— 被一到多个切面通知的对象 AOP 代理 —— AOP 框架基于切面规则创建的对象 织入 —— 创建通知对象关联切面和其他应用 通知 —— 对切入点进行的操作 前置通知 —— 在连接点之前执行的通知(@Before) 后置通知 —— 在连接点正常完成后执行的通知(@AfterReturning) 环绕通知 —— 在方法调用前后执行的通知(@Around) 异常通知 —— 方法抛出异常时执行的通知(@AfterThrowing) 最终通知 —— 从连接点退出后执行的通知(@After) Spring AOP 目标 纯 Java 实现。不需要特殊的编译过程。不需要控制类加载器层次结构,适合在 Servlet 容器或应用程序服务器中使用。 只支持方法执行连接点。如果需要字段拦截和更新连接点,考虑 AspectJ 之类的语言。 Spring AOP 不是提供最完整的 AOP 实现。其目标是提供 AOP 实现和 Spring IoC 之间的紧密集成。 AOP 代理 Spring AOP 默认使用标准 JDK 动态代理实现 AOP 代理。 Spring AOP 还可以使用CGLIB代理。 @Aspect 风格 激活 @AspectJ 支持 —— 通过自动代理,Spring 自动为被通知的 Bean 生成代理来拦截方法调用,确保按需执行通知 @Configuration @EnableAspectJAutoProxy public class AppConfig { } 定义一个切面 —— 在应用程序上下文中使用 @AspectJ 类定义 Bean 会被 Spring 自动检测到,并用于配置 Spring AOP @Aspect public class NotVeryUsefulAspect { } 定义一个切入点 —— 确定感兴趣的连接点,从而使我们能够控制何时执行通知。 @Pointcut("execution(* transfer(..))")// 切入点表达式 private void anyOldTransfer() {} execution —— 用于匹配方法执行连接点 within —— 将匹配限制为特定类型中的连接点 this —— 将匹配限制为 Bean 引用(AOP 代理)是给定类型实例的连接点 target —— 将匹配限制为目标对象是给定类型实例的连接点 args —— 将匹配限制为参数是给定类型实例的连接点 @target —— 将匹配限制为执行对象的类具有给定类型注解的连接点 @args —— 将匹配限制为传递的实际参数的运行时类型具有给定类型注解的连接点 @within —— 将匹配限制为与具有给定注解类型的连接点 @annotation —— 将匹配限制为连接点的主题具有给定类型注释的连接点 @Aspect public class SystemArchitecture { @Pointcut("within(com.xyz.someapp.web..*)") public void inWebLayer() {} @Pointcut("within(com.xyz.someapp.service..*)") public void inServiceLayer() {} @Pointcut("within(com.xyz.someapp.dao..*)") public void inDataAccessLayer() {} @Pointcut("execution(* com.xyz.someapp..service.*.*(..))") public void businessService() {} @Pointcut("execution(* com.xyz.someapp.dao.*.*(..))") public void dataAccessOperation() {} } execution(修饰符? 返回类型 包名?方法名称(参数类型) 异常类型?) //拦截任何公共方法的执行 execution(public * *(..)) //拦截任何以 set 开头的方法的执行 execution(* set*(..)) //拦截任何定义在 AccountService 接口中的方法的执行 execution(* com.xyz.service.AccountService.*(..)) //拦截任何定义在 service 包中的方法的执行 execution(* com.xyz.service.*.*(..)) //拦截任何定义在 service 包或者其一个子包中的方法的执行 execution(* com.xyz.service..*.*(..)) //拦截 service 包中的连接点 within(com.xyz.service.*) //拦截 service 包或者其一个子包中的连接点 within(com.xyz.service..*) //拦截实现 AccountService 接口的代理的连接点 this(com.xyz.service.AccountService) //拦截实现 AccountService 接口的目标对象的连接点 target(com.xyz.service.AccountService) //拦截参数只有一个 Serializable 的连接点 args(java.io.Serializable) //拦截目标对象有 @Transactional 注解的连接点 @target(org.springframework.transaction.annotation.Transactional) //拦截目标对象的声明类型有 @Transactional 注解的连接点 @within(org.springframework.transaction.annotation.Transactional) //拦截执行方法有 @Transactional 注解的连接点 @annotation(org.springframework.transaction.annotation.Transactional) //拦截参数只有一个 @Classified 注解的连接点 @args(com.xyz.security.Classified) 定义通知 —— 与切入点表达式相关联,并在匹配的方法执行之前、之后或前后运行 @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doAccessCheck() { // ... } @AfterReturning("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doAccessCheck() { // ... } @AfterReturning( pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()", returning="retVal") public void doAccessCheck(Object retVal) { // ... } @AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doRecoveryActions() { // ... } @AfterThrowing( pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()", throwing="ex") public void doRecoveryActions(DataAccessException ex) { // ... } @After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()") public void doReleaseLock() { // ... } @Around("com.xyz.myapp.SystemArchitecture.businessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.proceed(); // stop stopwatch return retVal; } JoinPoint 参数 —— ProceedingJoinPoint 是 JoinPoint 的子类 getArgs(): 返回方法参数 getThis(): 返回代理对象 getTarget(): 返回目标对象 getSignature(): 返回被通知方法的描述 toString(): 打印被通知方法的描述 传递参数给通知 @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)") public void validateAccount(Account account) { // ... } @Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)") private void accountDataAccessOperation(Account account) {} @Before("accountDataAccessOperation(account)") public void validateAccount(Account account) { // ... } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Auditable { AuditCode value(); } @Before("com.xyz.lib.Pointcuts.anyPublicMethod() && @annotation(auditable)") public void audit(Auditable auditable) { AuditCode code = auditable.value(); // ... } public interface Sample<T> { void sampleGenericMethod(T param); void sampleGenericCollectionMethod(Collection<T> param); } @Before("execution(* ..Sample+.sampleGenericMethod(*)) && args(param)") public void beforeSampleMethod(MyType param) { // Advice implementation } @Before("execution(* ..Sample+.sampleGenericCollectionMethod(*)) && args(param)") public void beforeSampleMethod(Collection<MyType> param) { // Advice implementation } @Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)", argNames="bean,auditable") public void audit(Object bean, Auditable auditable) { AuditCode code = auditable.value(); // ... use code and bean } //第一参数是 JoinPoint, ProceedingJoinPoint, 或者 JoinPoint.StaticPart 类型,argNames 中可以省略 @Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)", argNames="bean,auditable") public void audit(JoinPoint jp, Object bean, Auditable auditable) { AuditCode code = auditable.value(); // ... use code, bean, and jp } @Before("com.xyz.lib.Pointcuts.anyPublicMethod()") public void audit(JoinPoint jp) { // ... use jp } @Around("execution(List<Account> find*(..)) && " + "com.xyz.myapp.SystemArchitecture.inDataAccessLayer() && " + "args(accountHolderNamePattern)") public Object preProcessQueryPattern(ProceedingJoinPoint pjp, String accountHolderNamePattern) throws Throwable { String newPattern = preProcess(accountHolderNamePattern); return pjp.proceed(new Object[] {newPattern}); } 代理机制 Spring AOP 使用 JDK 动态代理或 CGLIB 为给定的目标对象创建代理。 如目标对象实现至少一个接口,则使用 JDK 动态代理。如目标对象没有实现任何接口,则创建一个 CGLIB 代理。 public class SimplePojo implements Pojo { public void foo() { // this next method invocation is a direct call on the 'this' reference this.bar(); } public void bar() { // some logic... } } public class Main { public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(new SimplePojo()); factory.addInterface(Pojo.class); factory.addAdvice(new RetryAdvice()); Pojo pojo = (Pojo) factory.getProxy(); // this is a method call on the proxy! pojo.foo(); } } API Pointcut public interface Pointcut { ClassFilter getClassFilter(); MethodMatcher getMethodMatcher(); } public interface ClassFilter { boolean matches(Class clazz); } public interface MethodMatcher { boolean matches(Method m, Class targetClass); boolean isRuntime(); boolean matches(Method m, Class targetClass, Object[] args); }

优秀的个人博客,低调大师

Spring 框架文档之核心技术—— Resource

Resource Resource 接口定义 public interface Resource extends InputStreamSource { /** * 返回此资源的 URL 句柄 */ URL getURL() throws IOException; /** * 返回此资源的 URI 句柄 */ URI getURI() throws IOException; /** * 返回此资源的 File 句柄 */ File getFile() throws IOException; /** * 创建此资源的关联资源 */ Resource createRelative(String relativePath) throws IOException; } public interface InputStreamSource { /** * 返回底层资源内容的 InputStream */ InputStream getInputStream() throws IOException; } 内置 Resource 实现者 UrlResource —— 封装 java.net.URL,用于访问通过URL访问的任何对象,例如 file:、http:、ftp: 等 ClassPathResource —— 使用线程上下文类加载器、给定的类加载器或给定的类从类路径加载资源。如 classpath: FileSystemResource —— 从文件系统加载资源 ServletContextResource —— 从 Web 应用根目录的相对路径中加载资源,支持 URL、流、File(资源位于文件系统)访问 InputStreamResource —— 在没有特定的资源实现时使用 ByteArrayResource —— 从任何给定的字节数组加载资源 ResourceLoader 返回资源类型确认 //对于 ClassPathXmlApplicationContext, 返回 ClassPathResource //对于 FileSystemXmlApplicationContext, 返回 FileSystemResource //对于 WebApplicationContext, 返回 ServletContextResource Resource template = ctx.getResource("some/resource/path/myTemplate.txt"); //指定 classpath:,返回 ClassPathResource Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt"); //指定 file:、http:,返回 UrlResource Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt"); Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt"); 与 ApplicationContext 协作 ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml"); //注意:FileSystemXmlApplicationContext 强制将 FileSystemResource 路径当作相对路径 ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml"); //如要使用绝对路径,推荐使用 file: 形式的 UrlResource ApplicationContext ctx = new FileSystemXmlApplicationContext("file:///conf/context.xml");

优秀的个人博客,低调大师

技术篇-HBase Coprocessor 的实现与应用

本次分享的内容主要分为以下五点: Coprocessor 简介 Endpoint 服务端实现 Endpoint 客户端实现 Observer 实现二级索引 Coprocessor 应用场景 1. Coprocessor 简介 HBase 协处理器的灵感来自于 Jeff Dean 09 年的演讲,根据该演讲实现类似于 Bigtable 的协处理器,包括以下特性:每个表服务器的任意子表都可以运行代码客户端的高层调用接口(客户端能够直接访问数据表的行地址,多行读写会自动分片成多个并行的 RPC 调用),提供一个非常灵活的、可用于建立分布式服务的数 据模型,能够自动化扩展、负载均衡、应用请求路由。HBase 的协处理器灵感来 自 Bigtable,但是实现细节不尽相同。HBase 建立框架为用户提供类库和运行时环境,使得代码能够在 HBase Regi

优秀的个人博客,低调大师

SpringBoot集成Redis来实现缓存技术方案

概述 在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求。 Redis简介 Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,Redis 的优势包括它的速度、支持丰富的数据类型、操作原子性,以及它的通用性。 案例整合 本案例是在之前一篇SpringBoot + Mybatis + RESTful的基础上来集成Redis的,所以大家如有什么不明白的地方可以前往https://my.oschina.net/feinik/blog/879266,由于篇幅原因这里不一一贴出所有的代码,具体完整案例代码可以看这里:https://github.com/AIFEINIK/SpringBoot-Learn/tree/master/spring-boot-redis2,关于Redis如何安装可自行google。 1、在Maven pom.xml文件中加入Redis包 <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>${boot.version}</version> </dependency> 2、SpringBoot配置文件中配置Redis连接(YAML方式配置) spring: application: name:spring-boot-redis redis: host:192.168.145.132 port:6379 timeout:20000 cluster: nodes:192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002 maxRedirects:6 pool: max-active:8 min-idle:0 max-idle:8 max-wait:-1 解释:本配置采用Redis一主三从的的配置方式来提高缓存的吞吐量 3、Redis配置类 @Configuration publicclassRedisConfig{ @Bean publicRedisTemplate<Object,Object>redisTemplate(RedisConnectionFactoryconnectionFactory){ RedisTemplate<Object,Object>template=newRedisTemplate<>(); template.setConnectionFactory(connectionFactory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializerserializer=newJackson2JsonRedisSerializer(Object.class); ObjectMappermapper=newObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); template.setValueSerializer(serializer); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(newStringRedisSerializer()); template.afterPropertiesSet(); returntemplate; } } 解释:SpringBoot提供了对Redis的自动配置功能,在RedisAutoConfiguration中默认为我们配置了JedisConnectionFactory(客户端连接)、RedisTemplate以及StringRedisTemplate(数据操作模板),其中StringRedisTemplate模板只针对键值对都是字符型的数据进行操作,本示例采用RedisTemplate作为数据操作模板,该模板默认采用JdkSerializationRedisSerializer的二进制数据序列化方式,为了方便演示本示例采用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值,使用StringRedisSerializer来序列化和反序列化redis的key值。 4、Service层应用缓存(注解方式) @Service publicclassPersonService{ @Autowired privatePersonRepopersonRepo; /** *@Cacheable应用到读取数据的方法上,先从缓存中读取,如果没有再从DB获取数据,然后把数据添加到缓存中 *unless表示条件表达式成立的话不放入缓存 *@paramusername *@return */ @Cacheable(value="user",key="#root.targetClass+#username",unless="#resulteqnull") publicPersongetPersonByName(Stringusername){ Personperson=personRepo.getPersonByName(username); returnperson; } /** *@CachePut应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存 *@paramperson *@return */ @CachePut(value="user",key="#root.targetClass+#result.username",unless="#personeqnull") publicPersonsavePerson(Personperson){ returnpersonRepo.savePerson(person); } /** *@CacheEvict应用到删除数据的方法上,调用方法时会从缓存中删除对应key的数据 *@paramusername *@return */ @CacheEvict(value="user",key="#root.targetClass+#username",condition="#resulteqtrue") publicbooleanremovePersonByName(Stringusername){ returnpersonRepo.removePersonByName(username)>0; } publicbooleanisExistPersonName(Personperson){ returnpersonRepo.existPersonName(person)>0; } } 解释: 1、这里的缓存key为简单的字符串组合,也可根据具体需要实现自定义的Key生成器,然后在注解中使用keyGenerator来引用。 2、Spring Cache提供了一些供我们使用的SpEL上下文数据,通过#来引用,具体可查看Spring官网:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#cache-spel-context。 5、数据访问资源类 @Component @Path("personMgr") publicclassPersonMgrResource{ @Autowired privatePersonServicepersonService; @GET @Path("getPersonByName") @Produces(MediaType.APPLICATION_JSON) publicJsonRespgetPersonByName(@QueryParam("username")Stringusername){ Personperson=personService.getPersonByName(username); returnJsonResp.success(person); } @POST @Path("removePersonByName") @Produces(MediaType.APPLICATION_JSON) publicJsonRespremovePersonByName(@QueryParam("username")Stringusername){ if(personService.removePersonByName(username)){ returnJsonResp.success(); } returnJsonResp.fail("系统错误!"); } @POST @Path("savePerson") @Produces(MediaType.APPLICATION_JSON) publicJsonRespsavePerson(Personperson){ if(personService.isExistPersonName(person)){ returnJsonResp.fail("用户名已存在!"); } if(personService.savePerson(person).getId()>0){ returnJsonResp.success(); } returnJsonResp.fail("系统错误!"); } } 6、通过postman工具来测试缓存是否生效 第一次访问查找用户: 第一次通过用户名称来查找用户可以看到是从库中查询的数据,我们可以通过RedisClient工具来查看数据已放入了缓存 第二次查找用户:发现服务端并未打印任何数据库查询日志,可以知道第二次查询是从缓存中查询得到的数据。 总结 本文介绍如何通过SpringBoot来一步步集成Redis缓存,关于Redis的使用它不仅可以用作缓存,还可以用来构建队列系统,Pub/Sub实时消息系统,分布式系统的的计数器应用,关于Redis更多的介绍,请前往查阅官方文档。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码