├── .gitignore ├── pom.xml ├── readme.txt ├── session共享.docx ├── src ├── main │ ├── java │ │ └── com │ │ │ └── yzb │ │ │ └── lee │ │ │ └── springsession │ │ │ ├── Application.java │ │ │ ├── config │ │ │ └── RedisConfig.java │ │ │ ├── dao │ │ │ ├── IUserDao.java │ │ │ └── impl │ │ │ │ └── UserDaoImpl.java │ │ │ ├── domain │ │ │ ├── ConsumerLoanInfo.java │ │ │ ├── DomainTest.java │ │ │ └── MyBean.java │ │ │ ├── exception │ │ │ └── LocalException.java │ │ │ ├── init │ │ │ ├── DaoSomethingAfterAppStart.java │ │ │ ├── DaoSomethingAfterAppStart2.java │ │ │ └── readme.txt │ │ │ ├── service │ │ │ ├── IRedisDataStructureService.java │ │ │ ├── IUserService.java │ │ │ └── impl │ │ │ │ ├── RedisDataStructureServiceImpl.java │ │ │ │ └── UserServiceImpl.java │ │ │ └── web │ │ │ ├── RedisDataStructureController.java │ │ │ ├── SampleController.java │ │ │ └── SpringRestTemplateController.java │ ├── resources │ │ ├── application.properties │ │ ├── logback.xml │ │ ├── redis │ │ │ └── redis.properties │ │ └── test │ │ │ └── test.properties │ └── webapp │ │ ├── META-INF │ │ └── MANIFEST.MF │ │ └── jsp │ │ └── index.jsp └── test │ └── java │ └── com │ └── yzb │ └── lee │ └── springsession │ └── SpringRestTemplateTest.java └── 常用注解.txt /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /.settings/ 3 | .classpath 4 | .project -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.yzb.lee 7 | spring-session2 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-session2 12 | http://maven.apache.org 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | org.springframework.boot 20 | spring-boot-starter-parent 21 | 1.5.9.RELEASE 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-data-redis 33 | 34 | 35 | 36 | org.springframework.session 37 | spring-session-data-redis 38 | 39 | 40 | 41 | com.alibaba 42 | fastjson 43 | 1.2.17 44 | 45 | 46 | 47 | org.codehaus.janino 48 | janino 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-maven-plugin 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | redis cluster在设计的时候,就考虑到了去中心化,去中间件,也就是说,集群中的每个节点都是平等的关系,都是对等的,每个节点都保存各自的数据和整个集群的状态。 2 | 每个节点都和其他所有节点连接,而且这些连接保持活跃,这样就保证了我们只需要连接集群中的任意一个节点,就可以获取到其他节点的数据. 3 | Redis 集群会把数据存在一个 master 节点,然后在这个 master 和其对应的salve 之间进行数据同步。当读取数据时,也根据一致性哈希算法到对应的 master节点获取数据。 4 | 只有当一个master挂掉之后,才会启动一个对应的 salve节点,充当 master 5 | 6 | HttpSession创建时机: server端程序调用 HttpServletRequest.getSession(true)这样的语句时才被创建 7 | 8 | spring-boot:用来简化Spring应用的搭建到开发的过程,减少Spring的配置文件,推崇习惯优先于配置”的原则 9 | spring-boot会基于已经添加jar依赖项,“猜”开发者想如何配置spring,从而加载相应的配置(spring-boot有自己的默认配置)和启动相应的容器 10 | 11 | spring-boot中使用spring-session 12 | 最简单配置:1、pom.xml中配置spring-session-data-redis依赖;2、application.properties中配置spring.session.store-type=redis。 13 | 以上配置默认连接的是本地的redis(localhost:6379),如需自定义连接,则需在application.properties中配置redis连接属性。 14 | pom.xml中有spring-session依赖,application.properties中必须配置spring.session.store-type属性来告诉spring以何种方式来存储session; 15 | spring.session.store-type=none则是告诉spring以默认方式存储session(session存放在servlet容器中) 16 | 17 | @EnableRedisHttpSession与@EnableCaching没关系 前者开启Session缓存,后者开启普通缓存; 不是说配置了@EnableCaching,@EnableRedisHttpSession才起作用 18 | 19 | redis集群启动:若集群已经已经在之前搭建好了,那么只需要启动各个节点即可,步骤2可以可以省略 20 | 1、节点启动 21 | 202节点 22 | [root@slave1 redis-3.2.10]# ./src/redis-server redis_cluster/7000/redis.conf 23 | [root@slave1 redis-3.2.10]# ./src/redis-server redis_cluster/7001/redis.conf 24 | [root@slave1 redis-3.2.10]# ./src/redis-server redis_cluster/7002/redis.conf 25 | 222节点 26 | [root@master redis-3.2.10]# ./src/redis-server redis_cluster/7003/redis.conf 27 | [root@master redis-3.2.10]# ./src/redis-server redis_cluster/7004/redis.conf 28 | [root@master redis-3.2.10]# ./src/redis-server redis_cluster/7005/redis.conf 29 | 2、创建集群 30 | [root@master redis-3.2.10]# ./src/redis-trib.rb create --replicas 1 192.168.11.202:7000 192.168.11.202:7001 192.168.11.202:7002 192.168.11.222:7003 192.168.11.222:7004 192.168.11.222:7005 31 | 连接redis集群 32 | 连接某个节点即可,h:节点ip, c:表示连接到集群, p:端口, a:集群密码 33 | [root@slave1 redis-3.2.10]# ./src/redis-cli -h 192.168.11.222 -c -p 7004 -a myredis 34 | 35 | 参考博客: 36 | http://blog.csdn.net/javaloveiphone/article/details/53187314 37 | 38 | spring rest异步请求 39 | SpringRestTemplateController,对应推送地址 40 | SpringRestTemplateTest,对应推送者 41 | 42 | -------------------------------------------------------------------------------- /session共享.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youzhibing/spring-session2/03790d0037aff8ab9e76bd5025779d183ac92671/session共享.docx -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/Application.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession; 2 | 3 | import org.springframework.boot.Banner; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | @Configuration 10 | @EnableAutoConfiguration 11 | //@ComponentScan(basePackages = { "com.yzb.lee.springsession.web", "com.yzb.lee.springsession.init"}) 12 | @ComponentScan 13 | // @Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器 14 | // @EnableAutoConfiguration:基于已经添加jar依赖项,SpringBoot“猜”你将如何想配置Spring。例如spring-boot-starter-web已经添加Tomcat和Spring MVC,这个注释自动将假设您正在开发一个web应用程序并添加相应的spring设置 15 | // @ComponentScan:告诉Spring 哪个packages的用注解标识的类会被spring自动扫描并且装入bean容器。 16 | // @Import: 支持导入配置类,也支持导入普通的java类,并将其声明成一个bean 17 | // @ImportResource: load XML configuration files,支持导入xml配置文件 18 | // @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan; @SpringBootApplication(scanBasePackages={}, excludeName={}) 19 | // 使用嵌入式容器时,可以使用@ServletComponentScan启用@WebServlet,@ WebFilter和@WebListener注释类的自动注册; @ServletComponentScan在独立的容器中将不起作用,容器的内置发现机制将被使用来代替它 20 | public class Application { 21 | 22 | public static void main(String[] args) { 23 | //SpringApplication.run(Application.class, args); 24 | 25 | 26 | SpringApplication app = new SpringApplication(Application.class); 27 | app.setBannerMode(Banner.Mode.OFF); // 是否打印banner 28 | app.setWebEnvironment(true); // 是否创建web环境 29 | // app.setApplicationContextClass(); // 指定spring应用上下文启动类 30 | app.run(args); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/config/RedisConfig.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.config; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.cache.CacheManager; 10 | import org.springframework.cache.annotation.EnableCaching; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.PropertySource; 13 | import org.springframework.data.redis.cache.RedisCacheManager; 14 | import org.springframework.data.redis.connection.RedisClusterConfiguration; 15 | import org.springframework.data.redis.connection.RedisConnectionFactory; 16 | import org.springframework.data.redis.connection.RedisNode; 17 | import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 18 | import org.springframework.data.redis.core.RedisTemplate; 19 | import org.springframework.data.redis.serializer.RedisSerializer; 20 | import org.springframework.data.redis.serializer.SerializationException; 21 | import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; 22 | import org.springframework.util.StringUtils; 23 | 24 | import redis.clients.jedis.JedisPoolConfig; 25 | 26 | import com.alibaba.fastjson.JSON; 27 | import com.alibaba.fastjson.serializer.SerializerFeature; 28 | import com.yzb.lee.springsession.exception.LocalException; 29 | 30 | @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 300) // session有效时长, 单位为s 31 | @EnableCaching // 开启缓存 32 | @PropertySource("redis/redis.properties") 33 | // @ConfigurationProperties(prefix="spring.redis") // 前缀配置, 这样配置可以将spring.redis.password的值赋值给属性password 34 | public class RedisConfig { 35 | 36 | private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class); 37 | 38 | /* 39 | * @Value("${spring.redis.host}") private String hostName; 40 | * 41 | * @Value("${spring.redis.port}") private int port; 42 | */ 43 | 44 | @Value("${spring.redis.password}") 45 | private String password; 46 | 47 | @Value("${spring.redis.timeout}") 48 | private int timeout; 49 | 50 | @Value("${spring.redis.pool.maxActive}") 51 | private int maxTotal; 52 | 53 | @Value("${spring.redis.pool.maxIdle}") 54 | private int maxIdle; 55 | 56 | @Value("${spring.redis.pool.minIdle}") 57 | private int minIdle; 58 | 59 | @Value("${spring.redis.pool.maxWaitMillis}") 60 | private long maxWaitMillis; 61 | 62 | @Value("${spring.redis.pool.numTestsPerEvictionRun}") 63 | private int numTestsPerEvictionRun; 64 | 65 | @Value("${spring.redis.pool.timeBetweenEvictionRunsMillis}") 66 | private long timeBetweenEvictionRunsMillis; 67 | 68 | @Value("${spring.redis.pool.minEvictableIdleTimeMillis}") 69 | private long minEvictableIdleTimeMillis; 70 | 71 | @Value("${spring.redis.pool.softMinEvictableIdleTimeMillis}") 72 | private long softMinEvictableIdleTimeMillis; 73 | 74 | @Value("${spring.redis.pool.testOnBorrow}") 75 | private boolean testOnBorrow; 76 | 77 | @Value("${spring.redis.pool.testWhileIdle}") 78 | private boolean testWhileIdle; 79 | 80 | @Value("${spring.redis.pool.testOnReturn}") 81 | private boolean testOnReturn; 82 | 83 | @Value("${spring.redis.pool.blockWhenExhausted}") 84 | private boolean blockWhenExhausted; 85 | 86 | @Value("${spring.redis.expire.time}") 87 | private int expireTime; 88 | 89 | @Value("${spring.cluster.host}") 90 | private String clusterHosts; 91 | 92 | @Value("${spring.cluster.port}") 93 | private String clusterPorts; 94 | 95 | /* 96 | * @Value("${spring.cluster.socketTimeout}") private int socketTimeout; 97 | * 98 | * @Value("${spring.cluster.maxAttempts}") private int maxAttempts; 99 | */ 100 | 101 | @Value("${spring.cluster.maxRedirects}") 102 | private int maxRedirects; 103 | 104 | @Value("${spring.cluster.usePool}") 105 | private boolean usePool; 106 | 107 | @Bean 108 | public CacheManager cacheManager(RedisTemplate redisTemplate) { 109 | LOGGER.info("CacheManager init......; expireTime = ", expireTime); 110 | RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); 111 | cacheManager.setDefaultExpiration(expireTime); // 设置缓存过期时间 112 | return cacheManager; 113 | } 114 | 115 | @SuppressWarnings("rawtypes") 116 | @Bean(name="redisTemplate") 117 | public RedisTemplate redisTemplate(RedisConnectionFactory cf, RedisSerializer redisSerializer) { 118 | RedisTemplate redisTemplate = new RedisTemplate(); 119 | redisTemplate.setConnectionFactory(cf); 120 | redisTemplate.setKeySerializer(redisSerializer); 121 | redisTemplate.setValueSerializer(redisSerializer); 122 | return redisTemplate; 123 | } 124 | 125 | @Bean 126 | public JedisConnectionFactory connectionFactory( 127 | RedisClusterConfiguration redisClusterConfig, 128 | JedisPoolConfig jedisPoolConfig) { 129 | JedisConnectionFactory connectionFactory = new JedisConnectionFactory( 130 | redisClusterConfig, jedisPoolConfig); 131 | connectionFactory.setUsePool(usePool); 132 | connectionFactory.setPassword(password); 133 | 134 | return connectionFactory; 135 | } 136 | 137 | @SuppressWarnings("rawtypes") 138 | @Bean 139 | public RedisSerializer redisSerializer() 140 | { 141 | return new RedisSerializer() 142 | { 143 | 144 | @Override 145 | public byte[] serialize(Object t) throws SerializationException 146 | { 147 | if (t == null) 148 | { 149 | return new byte[0]; 150 | } 151 | return JSON.toJSONString(t, SerializerFeature.WriteClassName) 152 | .getBytes(); 153 | } 154 | 155 | @Override 156 | public Object deserialize(byte[] bytes) 157 | throws SerializationException 158 | { 159 | if (bytes == null || bytes.length <= 0) 160 | { 161 | return null; 162 | } 163 | String str = new String(bytes); 164 | 165 | return (Object) JSON.parseObject(str, Object.class); 166 | } 167 | 168 | }; 169 | } 170 | 171 | // 单机连接池 172 | /* 173 | * @Bean public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig) { 174 | * JedisPool jedisPool = new JedisPool(jedisPoolConfig, hostName, port, 175 | * timeout, password); return jedisPool; } 176 | */ 177 | 178 | @Bean 179 | public JedisPoolConfig jedisPoolConfig() { 180 | JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); 181 | jedisPoolConfig.setMaxTotal(maxTotal); 182 | jedisPoolConfig.setMaxIdle(maxIdle); 183 | jedisPoolConfig.setMinIdle(minIdle); 184 | jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); 185 | jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun); 186 | jedisPoolConfig 187 | .setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); 188 | jedisPoolConfig 189 | .setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); 190 | jedisPoolConfig 191 | .setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis); 192 | jedisPoolConfig.setTestOnBorrow(testOnBorrow); 193 | jedisPoolConfig.setTestWhileIdle(testWhileIdle); 194 | jedisPoolConfig.setTestOnReturn(testOnReturn); 195 | jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted); 196 | 197 | return jedisPoolConfig; 198 | } 199 | 200 | @Bean 201 | public RedisClusterConfiguration jedisClusterConfiguration() { 202 | if (StringUtils.isEmpty(clusterHosts)) { 203 | LOGGER.info("redis集群主机未配置"); 204 | throw new LocalException("redis集群主机未配置"); 205 | } 206 | if (StringUtils.isEmpty(clusterPorts)) { 207 | LOGGER.info("redis集群端口未配置"); 208 | throw new LocalException("redis集群端口未配置"); 209 | } 210 | String[] hosts = clusterHosts.split(","); 211 | String[] portArray = clusterPorts.split(";"); 212 | if (hosts.length != portArray.length) { 213 | LOGGER.info("redis集群主机数与端口数不匹配"); 214 | throw new LocalException("redis集群主机数与端口数不匹配"); 215 | } 216 | Set redisNodes = new HashSet(); 217 | for (int i = 0; i < hosts.length; i++) { 218 | String ports = portArray[i]; 219 | String[] hostPorts = ports.split(","); 220 | for (String port : hostPorts) { 221 | RedisNode node = new RedisNode(hosts[i], Integer.parseInt(port)); 222 | redisNodes.add(node); 223 | } 224 | } 225 | LOGGER.info("Set : {}", JSON.toJSONString(redisNodes), true); 226 | 227 | RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(); 228 | redisClusterConfiguration.setMaxRedirects(maxRedirects); 229 | redisClusterConfiguration.setClusterNodes(redisNodes); 230 | 231 | return redisClusterConfiguration; 232 | } 233 | 234 | // redis集群 235 | /* 236 | * @Bean public JedisCluster jedisCluster(JedisPoolConfig jedisPoolConfig) { 237 | * if (StringUtils.isEmpty(clusterHosts)) { LOGGER.info("redis集群主机未配置"); 238 | * return null; } if (StringUtils.isEmpty(clusterPorts)) { 239 | * LOGGER.info("redis集群端口为配置"); return null; } String[] hosts = 240 | * clusterHosts.split(","); String[] portArray = clusterPorts.split(";"); if 241 | * (hosts.length != portArray.length) { LOGGER.info("redis集群主机数与端口数不匹配"); 242 | * return null; } Set jedisClusterNode = new 243 | * HashSet(); for (int i=0; i : {}", JSON.toJSONString(jedisClusterNode), 248 | * true); 249 | * 250 | * JedisCluster jedisCluster = new JedisCluster(jedisClusterNode, timeout, 251 | * socketTimeout, maxAttempts, password, jedisPoolConfig); return 252 | * jedisCluster; } 253 | */ 254 | } 255 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/dao/IUserDao.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.dao; 2 | 3 | public interface IUserDao { 4 | String getName(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/dao/impl/UserDaoImpl.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.dao.impl; 2 | 3 | import org.springframework.stereotype.Repository; 4 | 5 | import com.yzb.lee.springsession.dao.IUserDao; 6 | 7 | @Repository 8 | public class UserDaoImpl implements IUserDao { 9 | 10 | @Override 11 | public String getName() { 12 | return "name:" + System.currentTimeMillis(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/domain/ConsumerLoanInfo.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.domain; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class ConsumerLoanInfo { 6 | /** 7 | * 合同号 8 | */ 9 | private String appNo; 10 | /** 11 | * 借款金额 12 | */ 13 | private BigDecimal contractLmt; 14 | /** 15 | * 借款利率 16 | */ 17 | private BigDecimal interestRate; 18 | /** 19 | * 产品名称 20 | */ 21 | private String productName; 22 | /** 23 | * 产品编号 24 | */ 25 | private String productCd; 26 | /** 27 | * 放款金额 28 | */ 29 | private BigDecimal orderLmtAmt; 30 | /** 31 | * 银行编号 32 | */ 33 | private String bankCode; 34 | /** 35 | * 银行名称 36 | */ 37 | private String bankName; 38 | /** 39 | * 银行账户 40 | */ 41 | private String bankCardNo; 42 | /** 43 | * 银行预留号码 44 | */ 45 | private String bankCellPhone; 46 | /** 47 | * 银行卡持卡人姓名 48 | */ 49 | private String bankCustName; 50 | /** 51 | * 银行卡持卡人身份证 52 | */ 53 | private String bankCustId; 54 | /** 55 | * 用户名称 56 | */ 57 | private String name; 58 | /** 59 | * 性别 60 | */ 61 | private String gender; 62 | /** 63 | * 手机号 64 | */ 65 | private String cellPhone; 66 | /** 67 | * 身份证号 68 | */ 69 | private String idNo; 70 | /** 71 | * 贷款期数 72 | */ 73 | private int loanTerm; 74 | /** 75 | * 业务归属省份 76 | */ 77 | private String affProvince; 78 | /** 79 | * 业务归属城市 80 | */ 81 | private String affCity; 82 | 83 | public String getAppNo() { 84 | return appNo; 85 | } 86 | 87 | public void setAppNo(String appNo) { 88 | this.appNo = appNo; 89 | } 90 | 91 | public BigDecimal getContractLmt() { 92 | return contractLmt; 93 | } 94 | 95 | public void setContractLmt(BigDecimal contractLmt) { 96 | this.contractLmt = contractLmt; 97 | } 98 | 99 | public BigDecimal getInterestRate() { 100 | return interestRate; 101 | } 102 | 103 | public void setInterestRate(BigDecimal interestRate) { 104 | this.interestRate = interestRate; 105 | } 106 | 107 | public String getProductName() { 108 | return productName; 109 | } 110 | 111 | public void setProductName(String productName) { 112 | this.productName = productName; 113 | } 114 | 115 | public String getProductCd() { 116 | return productCd; 117 | } 118 | 119 | public void setProductCd(String productCd) { 120 | this.productCd = productCd; 121 | } 122 | 123 | public BigDecimal getOrderLmtAmt() { 124 | return orderLmtAmt; 125 | } 126 | 127 | public void setOrderLmtAmt(BigDecimal orderLmtAmt) { 128 | this.orderLmtAmt = orderLmtAmt; 129 | } 130 | 131 | public String getBankCode() { 132 | return bankCode; 133 | } 134 | 135 | public void setBankCode(String bankCode) { 136 | this.bankCode = bankCode; 137 | } 138 | 139 | public String getBankName() { 140 | return bankName; 141 | } 142 | 143 | public void setBankName(String bankName) { 144 | this.bankName = bankName; 145 | } 146 | 147 | public String getBankCardNo() { 148 | return bankCardNo; 149 | } 150 | 151 | public void setBankCardNo(String bankCardNo) { 152 | this.bankCardNo = bankCardNo; 153 | } 154 | 155 | public String getBankCellPhone() { 156 | return bankCellPhone; 157 | } 158 | 159 | public void setBankCellPhone(String bankCellPhone) { 160 | this.bankCellPhone = bankCellPhone; 161 | } 162 | 163 | public String getBankCustName() { 164 | return bankCustName; 165 | } 166 | 167 | public void setBankCustName(String bankCustName) { 168 | this.bankCustName = bankCustName; 169 | } 170 | 171 | public String getBankCustId() { 172 | return bankCustId; 173 | } 174 | 175 | public void setBankCustId(String bankCustId) { 176 | this.bankCustId = bankCustId; 177 | } 178 | 179 | public String getName() { 180 | return name; 181 | } 182 | 183 | public void setName(String name) { 184 | this.name = name; 185 | } 186 | 187 | public String getGender() { 188 | return gender; 189 | } 190 | 191 | public void setGender(String gender) { 192 | this.gender = gender; 193 | } 194 | 195 | public String getCellPhone() { 196 | return cellPhone; 197 | } 198 | 199 | public void setCellPhone(String cellPhone) { 200 | this.cellPhone = cellPhone; 201 | } 202 | 203 | public String getIdNo() { 204 | return idNo; 205 | } 206 | 207 | public void setIdNo(String idNo) { 208 | this.idNo = idNo; 209 | } 210 | 211 | public int getLoanTerm() { 212 | return loanTerm; 213 | } 214 | 215 | public void setLoanTerm(int loanTerm) { 216 | this.loanTerm = loanTerm; 217 | } 218 | 219 | public String getAffProvince() { 220 | return affProvince; 221 | } 222 | 223 | public void setAffProvince(String affProvince) { 224 | this.affProvince = affProvince; 225 | } 226 | 227 | public String getAffCity() { 228 | return affCity; 229 | } 230 | 231 | public void setAffCity(String affCity) { 232 | this.affCity = affCity; 233 | } 234 | } -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/domain/DomainTest.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.domain; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.PropertySource; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | @PropertySource("test/test.properties") 9 | // @ConfigurationProperties(prefix="domain.test") 10 | public class DomainTest { 11 | // test.properties中domain.test.name的值会自动注入到name属性中,domain.test.password的值会自动注入到password属性中, @Value都可以省略 12 | // setters 和 getters 需要在@ConfigurationProperties bean中创建! 与@Value注解相反 13 | @Value("${domain.test.name}") 14 | private String name; 15 | @Value("${domain.test.password}") 16 | private String password; 17 | 18 | // 此处的setter getter是用于object转json时用到, 如果只是用@Value来注入值的话是不需要setter、getter的 19 | public String getName() { 20 | System.out.println("get domain name"); 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | System.out.println("set domain name"); 26 | this.name = name; 27 | } 28 | public String getPassword() { 29 | return password; 30 | } 31 | public void setPassword(String password) { 32 | this.password = password; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/domain/MyBean.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.domain; 2 | 3 | import java.util.List; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.ApplicationArguments; 9 | import org.springframework.stereotype.Component; 10 | 11 | import com.alibaba.fastjson.JSON; 12 | 13 | // 一般用不到, 用于接收启动命令带的参数 14 | @Component 15 | public class MyBean { 16 | 17 | private static final Logger LOGGER = LoggerFactory.getLogger(MyBean.class); 18 | 19 | // The ApplicationArguments interface provides access to both the raw String[] arguments as well as parsed option and non-option arguments 20 | @Autowired 21 | public MyBean(ApplicationArguments args) { 22 | boolean debug = args.containsOption("debug"); 23 | List files = args.getNonOptionArgs(); 24 | // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"] 25 | LOGGER.info("获取命令参数, debug={}", JSON.toJSONString(debug)); 26 | LOGGER.info("获取命令参数, 文件路径数组={}",JSON.toJSONString(files, true)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/exception/LocalException.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.exception; 2 | 3 | public class LocalException extends RuntimeException { 4 | 5 | private static final long serialVersionUID = 1L; 6 | 7 | public LocalException(String message) { 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/init/DaoSomethingAfterAppStart.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.init; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.core.annotation.Order; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | @Order(value = 1) 12 | public class DaoSomethingAfterAppStart implements CommandLineRunner { 13 | 14 | private static final Logger LOGGER = LoggerFactory.getLogger(DaoSomethingAfterAppStart.class); 15 | 16 | @Value("${spring.redis.host}") 17 | private String redisHost; 18 | 19 | @Override 20 | public void run(String... args) throws Exception { 21 | LOGGER.info("应用启动之后做某些特定的事; order=1; args是应用启动时附带的参数, redis:{}",redisHost); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/init/DaoSomethingAfterAppStart2.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.init; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.boot.ApplicationArguments; 6 | import org.springframework.boot.ApplicationRunner; 7 | import org.springframework.core.annotation.Order; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | @Order(value = 2) 12 | public class DaoSomethingAfterAppStart2 implements ApplicationRunner { 13 | 14 | private static final Logger LOGGER = LoggerFactory.getLogger(DaoSomethingAfterAppStart2.class); 15 | 16 | @Override 17 | public void run(ApplicationArguments args) throws Exception { 18 | LOGGER.info("应用启动之后做某些特定的事; order=2; args是应用启动时附带的参数"); 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/init/readme.txt: -------------------------------------------------------------------------------- 1 | 应用启动之后做的事 -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/service/IRedisDataStructureService.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.service; 2 | 3 | import java.util.List; 4 | 5 | public interface IRedisDataStructureService { 6 | 7 | /** 8 | * list 添加元素 9 | * @param userId 10 | * @param message 11 | * @return 12 | */ 13 | long pushLink(String userId, String message); 14 | 15 | /** 16 | * list 移除元素 17 | * @param userId 18 | * @return 19 | */ 20 | String popLink(String userId); 21 | 22 | /** 23 | * list 元素个数 24 | * @param userId 25 | * @return 26 | */ 27 | long sizeLink(String userId); 28 | 29 | /** 30 | * 全部元素 31 | * @param userId 32 | * @return 33 | */ 34 | List allLink(String userId); 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/service/IUserService.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.service; 2 | 3 | public interface IUserService { 4 | String getName(int id); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/service/impl/RedisDataStructureServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.service.impl; 2 | 3 | import java.util.List; 4 | 5 | import javax.annotation.Resource; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.data.redis.core.ListOperations; 10 | import org.springframework.data.redis.core.RedisTemplate; 11 | import org.springframework.stereotype.Service; 12 | 13 | import com.yzb.lee.springsession.service.IRedisDataStructureService; 14 | 15 | @Service 16 | public class RedisDataStructureServiceImpl implements IRedisDataStructureService { 17 | 18 | @Autowired 19 | @Qualifier("redisTemplate") // 这里需要指定名称;spring默认会启动stringRedisTemplate,RedisConfig中配置了redisTemplate, spring不知道在两者之中选择谁 20 | private RedisTemplate template; 21 | 22 | // inject the template as ListOperations 23 | @Resource(name = "redisTemplate") 24 | private ListOperations listOps; 25 | 26 | @Override 27 | public long pushLink(String userId, String message) { 28 | return listOps.leftPush(userId, message); 29 | } 30 | 31 | @Override 32 | public String popLink(String userId) { 33 | return listOps.rightPop(userId); 34 | } 35 | 36 | @Override 37 | public long sizeLink(String userId) { 38 | return listOps.size(userId); 39 | } 40 | 41 | @Override 42 | public List allLink(String userId) { 43 | return listOps.range(userId, 0, listOps.size(userId)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.service.impl; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.cache.annotation.Cacheable; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.yzb.lee.springsession.dao.IUserDao; 10 | import com.yzb.lee.springsession.service.IUserService; 11 | 12 | @Service 13 | public class UserServiceImpl implements IUserService { 14 | 15 | private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); 16 | 17 | @Autowired 18 | private IUserDao userDao; 19 | 20 | @Override 21 | @Cacheable(value="nameCache",key="#id + 'getName'") 22 | // @CachePut 能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用 23 | // @CachEvict 能够根据一定的条件对缓存进行清空 24 | public String getName(int id) { 25 | LOGGER.info("调用了dao层"); 26 | return userDao.getName(); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/web/RedisDataStructureController.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.web; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestMethod; 8 | import org.springframework.web.bind.annotation.RequestParam; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import com.yzb.lee.springsession.service.IRedisDataStructureService; 12 | 13 | @RestController 14 | @RequestMapping("/redisDateStructure") 15 | public class RedisDataStructureController { 16 | 17 | @Autowired 18 | private IRedisDataStructureService redisDataStructureService; 19 | 20 | @RequestMapping(value={"/push"}, method=RequestMethod.POST) 21 | public long push(@RequestParam(required=true) String userId, @RequestParam(required=true) String message) { 22 | return redisDataStructureService.pushLink(userId, message); 23 | } 24 | 25 | @RequestMapping(value={"/pop"}, method=RequestMethod.POST) 26 | public String pop(@RequestParam(required=true) String userId) { 27 | return redisDataStructureService.popLink(userId); 28 | } 29 | 30 | @RequestMapping(value={"/size"}, method=RequestMethod.POST) 31 | public long size(@RequestParam(required=true) String userId) { 32 | return redisDataStructureService.sizeLink(userId); 33 | } 34 | 35 | @RequestMapping(value={"/all"}, method=RequestMethod.POST) 36 | public List all(@RequestParam(required=true) String userId) { 37 | return redisDataStructureService.allLink(userId); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/web/SampleController.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.web; 2 | 3 | import java.util.Enumeration; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import javax.servlet.http.HttpSession; 10 | 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RequestMethod; 14 | import org.springframework.web.bind.annotation.RequestParam; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import com.yzb.lee.springsession.domain.DomainTest; 18 | import com.yzb.lee.springsession.service.IUserService; 19 | 20 | @RestController 21 | @RequestMapping("/hello") 22 | // @EnableConfigurationProperties(DomainTest.class) // 这个注解告诉Spring Boot 使能支持@ConfigurationProperties,让@ConfigurationProperties beans被添加 23 | // 用@Configuration或者 @Component注解也能使@ConfigurationProperties beans 被添加 24 | public class SampleController { 25 | 26 | @Autowired 27 | private IUserService userService; 28 | 29 | @Autowired 30 | private DomainTest domain; 31 | 32 | @RequestMapping("/greet") 33 | Map greet(HttpServletRequest req, HttpServletResponse resp) { 34 | String attributeName = req.getParameter("attributeName"); 35 | String attributeValue = req.getParameter("attributeValue"); 36 | HttpSession session = req.getSession(); 37 | session.setAttribute(attributeName, attributeValue); 38 | 39 | Enumeration attrs = session.getAttributeNames(); 40 | Map sessionAttrValues = new HashMap(); 41 | while( attrs.hasMoreElements()) { 42 | String sessionName=(String)attrs.nextElement(); 43 | sessionAttrValues.put(sessionName, session.getAttribute(sessionName).toString()); 44 | 45 | } 46 | 47 | return sessionAttrValues; 48 | } 49 | 50 | @RequestMapping(value={"/name"}, method=RequestMethod.POST) 51 | String getName(@RequestParam(required=true) int id) { 52 | return userService.getName(id); 53 | } 54 | 55 | @RequestMapping(value={"/domain"}) 56 | DomainTest getDomain() { 57 | return domain; 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/com/yzb/lee/springsession/web/SpringRestTemplateController.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession.web; 2 | 3 | import org.springframework.web.bind.annotation.RequestBody; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | import com.alibaba.fastjson.JSON; 8 | import com.yzb.lee.springsession.domain.ConsumerLoanInfo; 9 | 10 | @RestController 11 | @RequestMapping("/rest") 12 | public class SpringRestTemplateController { 13 | 14 | // @RequestBody ConsumerLoanInfo loanInfo可以改写成@RequestBody JSONObject requestBody, JSONObject是一种通用写法, 优先选用前者 15 | @RequestMapping("/handle") 16 | String consumerLoanHandle(@RequestBody ConsumerLoanInfo loanInfo) throws InterruptedException { 17 | System.out.println(JSON.toJSONString(loanInfo,true)); 18 | Thread.sleep(10000); 19 | return "success"; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #存放全局配置 2 | 3 | #web 端口 4 | server.port=8081 -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | INFO 11 | ACCEPT 12 | DENY 13 | 14 | ${LOG_NAME}/logs/info/info.log 15 | 16 | %d{yyyy-MM-dd HH:mm:ss}|%p|%logger|%msg%n 17 | 18 | 19 | 1 20 | 10 21 | ${LOG_NAME}/logs/info/info.%i.log 22 | 23 | 25 | 20MB 26 | 27 | 28 | 29 | 31 | 32 | 33 | warn 34 | 35 | ${LOG_NAME}/logs/warn/warn.log 36 | 37 | %d{yyyy-MM-dd HH:mm:ss}|%p|%logger|%msg%n 38 | 39 | 40 | 1 41 | 10 42 | ${LOG_NAME}/logs/warn/warn.%i.log 43 | 44 | 46 | 20MB 47 | 48 | 49 | 50 | 51 | 52 | %d{yyyy-MM-dd HH:mm:ss}|%p|%logger|%msg%n 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /src/main/resources/redis/redis.properties: -------------------------------------------------------------------------------- 1 | # REDIS (RedisProperties) 2 | # Redis数据库索引(默认为0) 3 | #spring.redis.database=0 4 | # Redis服务器地址 5 | spring.redis.host=192.168.11.222 6 | # Redis服务器连接端口 7 | spring.redis.port=6379 8 | # Redis服务器连接密码 9 | spring.redis.password=myredis 10 | # 连接超时时间(毫秒) 11 | spring.redis.timeout=0 12 | spring.redis.expire.time=300 13 | 14 | # 连接池 15 | # 连接池最大连接数(使用负值表示没有限制) 16 | spring.redis.pool.maxActive=150 17 | # 连接池中的最大空闲连接 18 | spring.redis.pool.maxIdle=10 19 | # 连接池中的最小空闲连接 20 | spring.redis.pool.minIdle=1 21 | # 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 22 | spring.redis.pool.maxWaitMillis=3000 23 | # 每次释放连接的最大数目 24 | spring.redis.pool.numTestsPerEvictionRun=50 25 | # 释放连接的扫描间隔(毫秒) 26 | spring.redis.pool.timeBetweenEvictionRunsMillis=3000 27 | # 连接最小空闲时间(毫秒) 28 | spring.redis.pool.minEvictableIdleTimeMillis=1800000 29 | # 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放(毫秒) 30 | spring.redis.pool.softMinEvictableIdleTimeMillis=10000 31 | # 在获取连接的时候检查有效性, 默认false 32 | spring.redis.pool.testOnBorrow=true 33 | # 在空闲时检查有效性, 默认false 34 | spring.redis.pool.testWhileIdle=true 35 | # 在归还给pool时,是否提前进行validate操作 36 | spring.redis.pool.testOnReturn=true 37 | # 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true 38 | spring.redis.pool.blockWhenExhausted=true 39 | 40 | #session 41 | spring.session.store-type=redis 42 | 43 | #cluster 44 | spring.cluster.host=192.168.11.202,192.168.11.222 45 | spring.cluster.port=7000,7001,7002;7003,7004,7005 46 | #redis读写超时时间(毫秒) 47 | spring.cluster.socketTimeout=50000 48 | #最大尝试连接次数 49 | spring.cluster.maxAttempts=10 50 | #最大重定向次数 51 | spring.cluster.maxRedirects=5 52 | # 53 | spring.cluster.usePool=true -------------------------------------------------------------------------------- /src/main/resources/test/test.properties: -------------------------------------------------------------------------------- 1 | #测试 2 | domain.test.name=yzb 3 | domain.test.password=123456 -------------------------------------------------------------------------------- /src/main/webapp/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youzhibing/spring-session2/03790d0037aff8ab9e76bd5025779d183ac92671/src/main/webapp/META-INF/MANIFEST.MF -------------------------------------------------------------------------------- /src/main/webapp/jsp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 2 | <%@ taglib prefix="wj" uri="http://www.webjars.org/tags" %> 3 | 4 | 5 | 6 | Session Attributes 7 | 8 | "> 9 | 14 | 15 | 16 |
17 |

Description

18 |

This application demonstrates how to use a Redis instance to back your session. Notice that there is no JSESSIONID cookie. We are also able to customize the way of identifying what the requested session id is.

19 | 20 |

Try it

21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 |
Attribute NameAttribute Value
48 |
49 | 50 | 51 | -------------------------------------------------------------------------------- /src/test/java/com/yzb/lee/springsession/SpringRestTemplateTest.java: -------------------------------------------------------------------------------- 1 | package com.yzb.lee.springsession; 2 | 3 | import java.math.BigDecimal; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.http.HttpEntity; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.util.concurrent.ListenableFuture; 10 | import org.springframework.util.concurrent.ListenableFutureCallback; 11 | import org.springframework.web.client.AsyncRestTemplate; 12 | 13 | import com.yzb.lee.springsession.domain.ConsumerLoanInfo; 14 | 15 | public class SpringRestTemplateTest { 16 | private static final Logger LOGGER = LoggerFactory.getLogger(SpringRestTemplateTest.class); 17 | private static final String OBJ_URL = "http://localhost:8081/rest/handle"; 18 | 19 | public static void main(String[] args) { 20 | ConsumerLoanInfo info = queryConsumerLoan(); 21 | doPush(info); 22 | } 23 | private static ConsumerLoanInfo queryConsumerLoan() { 24 | ConsumerLoanInfo loanInfo = new ConsumerLoanInfo(); 25 | loanInfo.setAffCity("深圳市"); 26 | loanInfo.setAffProvince("广东省"); 27 | loanInfo.setAppNo("201802499349340"); 28 | loanInfo.setBankCardNo("66600049329049983498"); 29 | loanInfo.setBankCellPhone("15174480311"); 30 | loanInfo.setBankCode("23294"); 31 | loanInfo.setBankCustId("430682199212159130"); 32 | loanInfo.setBankCustName("李隆基"); 33 | loanInfo.setBankName("不知道什么行"); 34 | loanInfo.setCellPhone("15174480311"); 35 | loanInfo.setContractLmt(new BigDecimal(20000.00)); 36 | loanInfo.setGender("男"); 37 | loanInfo.setIdNo("430682199212159130"); 38 | loanInfo.setInterestRate(new BigDecimal(0.16)); 39 | loanInfo.setLoanTerm(36); 40 | loanInfo.setName("李隆基"); 41 | loanInfo.setOrderLmtAmt(new BigDecimal(0.16)); 42 | loanInfo.setProductCd("000408"); 43 | loanInfo.setProductName("驾费分期"); 44 | 45 | return loanInfo; 46 | } 47 | /** 48 | * 信息推送 49 | * @param info 推送的信息实体 50 | */ 51 | private static void doPush(ConsumerLoanInfo info) { 52 | AsyncRestTemplate restTemplate = new AsyncRestTemplate(); 53 | HttpEntity httpEntity = new HttpEntity<>(info); 54 | ListenableFuture> forEntity = restTemplate.postForEntity(OBJ_URL, httpEntity, String.class); 55 | 56 | //异步调用后的回调函数 57 | forEntity.addCallback(new ListenableFutureCallback>() { 58 | //调用失败 59 | @Override 60 | public void onFailure(Throwable ex) { 61 | LOGGER.error("信息推送失败: {}", ex); 62 | } 63 | //调用成功 64 | @Override 65 | public void onSuccess(ResponseEntity result) { 66 | LOGGER.info("信息推送成功: {}", result.getBody()); 67 | } 68 | }); 69 | LOGGER.info("信息推送结束......"); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /常用注解.txt: -------------------------------------------------------------------------------- 1 | 声明Bean的注解: 2 | @Component : 组件,没有明确的角色 3 | @Service : 在业务逻辑层(service层)使用 4 | @Repository : 在数据访问层(dao层)使用. 5 | @Controller : 在展现层(MVC--SpringMVC)使用 6 | 7 | 注入Bean的注解: 8 | @Aautowired : Spring提供的注解. 9 | @Inject : JSR-330提供的注解 10 | @Resource : JSR-250提供的注解 11 | 12 | 配置文件的注解: 13 | @Configuration : 声明当前类是个配置类,相当于一个Spring配置的xml文件. 14 | @ComponentScan (cn.test.demo): 自动扫描包名下所有使用 @Component @Service @Repository @Controller 的类,并注册为Bean 15 | @WiselyConfiguration : 组合注解 可以替代 @Configuration和@ComponentScan 16 | @Bean : 注解在方法上,声明当前方法的返回值为一个Bean. 17 | @Bean(initMethod="aa",destroyMethod="bb")--> 指定 aa和bb方法在构造之后.Bean销毁之前执行. 18 | 19 | AOP切面编程注解: 20 | @Aspect : 声明这是一个切面 21 | @After @Before @Around 定义切面,可以直接将拦截规则(切入点 PointCut)作为参数 22 | @PointCut : 专门定义拦截规则 然后在 @After @Before. @Around 中调用 23 | @Transcational : 事务处理 24 | @Cacheable : 数据缓存 25 | @EnableAaspectJAutoProxy : 开启Spring 对 这个切面(Aspect )的支持 26 | @Target (ElementType.TYPE):元注解,用来指定注解修饰类的那个成员 -->指定拦截规则 27 | @Retention(RetentionPolicy.RUNTIME) --->当定义的注解的@Retention为RUNTIME时,才能够通过运行时的反射机制来处理注解.-->指定拦截规则 28 | 29 | Spring 常用配置: 30 | @import :导入配置类 31 | @Scope : 新建Bean的实例 @Scope("prototype") 声明Scope 为 Prototype 32 | @Value : 属性注入 33 | @Value ("我爱你") --> 普通字符串注入 34 | @Value ("#{systemProperties['os.name']}") -->注入操作系统属性 35 | @Value ("#{ T (java.lang.Math).random() * 100.0 }") --> 注入表达式结果 36 | @Value ("#{demoService.another}") --> 注入其他Bean属性 37 | @Value ("classpath:com/wisely/highlight_spring4/ch2/el/test.txt" ) --> 注入文件资源 38 | @Value ("http://www.baidu.com")-->注入网址资源 39 | @Value ("${book.name}" ) --> 注入配置文件 注意: 使用的是$ 而不是 # 40 | @PostConstruct : 在构造函数执行完之后执行 41 | @PreDestroy : 在 Bean 销毁之前执行 42 | @ActiveProfiles : 用来声明活动的 profile 43 | @profile: 为不同环境下使用不同的配置提供了支持 44 | @Profile("dev") .......对方法名为 dev-xxxx的方法提供实例化Bean 45 | @EnableAsync : 开启异步任务的支持(多线程) 46 | @Asyns : 声明这是一个异步任务,可以在类级别 和方法级别声明. 47 | @EnableScheduling : 开启对计划任务的支持(定时器) 48 | @Scheduled : 声明这是一个计划任务 支持多种计划任务,包含 cron. fixDelay fixRate 49 | @Scheduled (dixedDelay = 5000) 通过注解 定时更新 50 | @Conditional : 条件注解,根据满足某一特定条件创建一个特定的Bean 51 | @ContextConfiguration : 加载配置文件 52 | @ContextConfiguration(classes = {TestConfig.class}):@ContextConfiguration用来加载ApplicationContext classes属性用来加载配置类 53 | @WebAppCofiguration : 指定加载 ApplicationContext是一个WebApplicationContext 54 | 55 | @Enable*注解: 56 | @EnableAsync : 开启异步任务的支持(多线程) 57 | @EnableScheduling : 开启对计划任务的支持(定时器) 58 | @EnableWebMVC : 开启对Web MVC 的配置支持 59 | @EnableAaspectJAutoProxy : 开启Spring 对 这个切面(Aspect )的支持 60 | @EnableConfigurationProperties 开启对@ConfigurationProperties注解配置Bean的支持 61 | @EnableJpaRepositories : 开启对Spring Data JAP Repository 的支持 62 | @EnableTransactionManagement 开启对注解式事物的支持 63 | @EnableCaching开启注解是缓存的支持. 64 | @EnableDiscoveryClient 让服务发现服务器,使用服务器.Spring cloud 实现服务发现 65 | @EnableEurekaServer 注册服务器 spring cloud 实现服务注册@ 66 | @EnableScheduling 让spring可以进行任务调度,功能类似于spring.xml文件中的命名空间 67 | @EnableCaching 开启Cache缓存支持; 68 | 69 | SpringMVC 常用注解: 70 | @Controller : 注解在类上 声明这个类是springmvc里的Controller,将其声明为一个spring的Bean. 71 | @RequestMapping :可以注解在类上和方法上 映射WEB请求(访问路径和参数) 72 | @RequestMapping(value= "/convert",produces+{"application/x-wisely"}) 设置访问URL 返回值类型 73 | @ResponseBody : 支持将返回值放入response体内 而不是返回一个页面(返回的是一个组数据) 74 | @RequestBody : 允许request的参数在request体中,而不是直接连接在地址后面 次注解放置在参数前 75 | @Path Variable : 用来接收路径参数 如/test/001,001为参数,次注解放置在参数前 76 | @RestController : @Controller + @ResponseBody 组合注解 77 | @ControllerAdvice : 通过@ControllerAdvice可以将对已控制器的全局配置放置在同一个位置 78 | @ExceptionHandler : 用于全局处理控制器的异常 79 | @ExceptionHandier(value=Exception.class) -->通过value属性可过滤拦截器条件,拦截所有的异常 80 | @InitBinder : 用来设置WebDataBinder , WebDataBinder用来自动绑定前台请求参数到Model中. 81 | @ModelAttrbuute : 绑定键值对到Model中, 82 | @RunWith : 运行器 83 | @RunWith(JUnit4.class)就是指用JUnit4来运行 84 | @RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境 85 | @RunWith(Suite.class)的话就是一套测试集合, 86 | @WebAppConfiguration("src/main/resources") : 注解在类上,用来声明加载的ApplicationContex 是一个WebApplicationContext ,它的属性指定的是Web资源的位置,默认为 src/main/webapp ,自定义修改为 resource 87 | @Before : 在 xxx 前初始化 88 | 89 | Spring Boot 注解: 90 | @SpringBootApplication : 是Spring Boot 项目的核心注解 主要目的是开启自动配置; @SpringBootApplication注解是一个组合注解,主要组合了@Configuration .+@EnableAutoConfiguration.+@ComponentScan 91 | @Value : 属性注入,读取properties或者 Yml 文件中的属性 92 | @ConfigurationProperties : 将properties属性和一个Bean及其属性关联,从而实现类型安全的配置 93 | @ConfigurationProperties(prefix = "author",locations = {"classpath:config/author.properties"}),通过@ConfigurationProperties加载配置,通过prefix属性指定配置前缀,通过location指定配置文件位置 94 | @EnableAutoConfiguration 注解:作用在于让 Spring Boot根据应用所声明的依赖来对 Spring 框架进行自动配置;这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。 95 | @Configuration 注解,以明确指出该类是 Bean 配置的信息源 96 | @ComponentScan 注解会告知Spring扫描指定的包来初始化Spring Bean这能够确保我们声明的Bean能够被发现。 97 | @ImportResource 注解加载XML配置文件 98 | @EnableAutoConfiguration(exclude={xxxx.class}) 禁用特定的自动配置 99 | @SpringBootApplication 注解等价于以默认属性使用@Configuration,@EnableAutoConfiguration和 @ComponentScan。 100 | 101 | 102 | @SuppressWarnings注解 103 | @SuppressWarnings("unchecked"),告诉编译器忽略 unchecked 警告信息,如使用 list ArrayList等未进行参数化产生的警告信息 104 | @SuppressWarnings("serial"),如果编译器出现这样的警告信息: The serializable class WmailCalendar does not declare a static final serialVersionUID field of type long 使用这个注释将警告信息去掉。 105 | @SuppressWarnings("deprecation"),如果使用了使用@Deprecated注释的方法,编译器将出现警告信息。使用这个注释将警告信息去掉。 106 | @SuppressWarnings("unchecked", "deprecation"),告诉编译器同时忽略unchecked和deprecation的警告信息。 107 | @SuppressWarnings(value={"unchecked", "deprecation"})等同于@SuppressWarnings("unchecked", "deprecation") --------------------------------------------------------------------------------