spring cloud微服务快速开始

快速搭建一个springcloud微服务

引入依赖

<dependency>
    <groupId>com.wueasy</groupId>
    <artifactId>wueasy-base</artifactId>
</dependency>
<dependency>
    <groupId>com.wueasy</groupId>
    <artifactId>wueasy-cloud-web</artifactId>
</dependency>
<dependency>
    <groupId>com.wueasy</groupId>
    <artifactId>wueasy-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

配置

注册中心

eureka:
  instance:
    prefer-ip-address: true
    lease-expiration-duration-in-seconds: 15 #服务过期时间配置,超过这个时间没有接收到心跳EurekaServer就会将这个实例剔除
    lease-renewal-interval-in-seconds: 5 #服务刷新时间配置,每隔这个时间会主动心跳一次
  client:
    registryFetchIntervalSeconds: 5 #client刷新本地缓存时间
    serviceUrl:
      defaultZone: http://127.0.0.1:8000/eureka/

feign:
  client:
    config:
      default:
        connectTimeout: 5000 #连接超时时间
        readTimeout: 5000    #请求与响应的时间间隔阈值

redis配置

配置sesson连接信息

wueasy :
  data:
    redis: #redis配置
      session:
        database : 1 #数据库索引(默认为0)
        host : 127.0.0.1 #服务器地址
        port : 6379 #服务器连接端口
        password : 123456  #服务器连接密码(默认为空)
        pool : #连接池配置
          maxIdle : 8 # 连接池中的最大空闲连接,默认值也是8。
          minIdle : 0 #连接池中的最小空闲连接,默认值也是0。
          maxTotal : 2000 # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
          maxWaitMillis : 1000 # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
        timeout : 3000 #连接超时时间(毫秒)

启动类

@SpringBootApplication(exclude = {RedisAutoConfiguration.class,RedisRepositoriesAutoConfiguration.class})
@EnableFeignClients
@ComponentScan(basePackages="com.wueasy")
@EnableDiscoveryClient
public class Application
{
    public static void main(String[] args) {
        //负责启动引导应用程序
        SpringApplication.run(Application.class, args);
    }

}

登录接口示例

@RestController
public class LoginController
{

    @Autowired
    @Qualifier("sessionStringRedisTemplate")
    private StringRedisTemplate sessionRedisTemplate;

    /**
     * 登录
     * @author: fallsea
     * @return
     */
    @RequestMapping(value= "/login",method={RequestMethod.POST},produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<String> login(HttpServletRequest request,HttpServletResponse response,@RequestBody @Valid LoginDto dto)
    {

        System.err.println(UserHelper.getRequestId()+"------"+UserHelper.getUserId());

        if(!"admin".equals(dto.getAccountNo()) || !"123456".equals(dto.getPassword())) {
            throw new InvokeException(-1,"用户名或密码不正确");
        }


        //登录,创建一个session,并返回用户信息,权限信息
        Session<String> session = new Session<>();

        User user = new User();
        user.setIsSystem(true);//是否超级管理员(1.是)
        user.setUserId("1");
        user.setUsername("wueasy");
        session.setUser(user);

        //菜单权限
        List<Menu> menuList = new ArrayList<>(); 
        session.setMenuList(menuList);


        //可访问的url地址权限,用户有权限的url地址集合
        Set<String> linkUrlSetAll = new HashSet<String>();
        session.setAuthorizeUrlList(linkUrlSetAll);


        //拓展信息对象
        session.setExtendedObject("1234");

        String token = StringHelper.getUuid();
        sessionRedisTemplate.opsForValue().set(WueasyCloudCommon.getSessionRedisKey(token), JsonHelper.toJsonString(session),30,TimeUnit.MINUTES);

        return new Result<String>().setData(token);
    }

    @RequestMapping(value= "/logout",method={RequestMethod.POST},produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<Void> logout(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        if(StringHelper.isNotBlank(token)) {
            boolean b = sessionRedisTemplate.delete(WueasyCloudCommon.getSessionRedisKey(token));

            if(b) {
                //实时退出
                sessionRedisTemplate.convertAndSend(WueasyCloudCommon.SESSION_TOPIC_LOGOT_REDIS_KEY, token);
            }
        }
        return new Result<Void>();
    }


    @RequestMapping(value= "/generateUuid",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<String> generateUuid(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        String uuid = StringHelper.getUuid();
        sessionRedisTemplate.opsForValue().set(WueasyCloudCommon.getTokenTransformRedisKey(uuid), token,10,TimeUnit.MINUTES);
        return new Result<String>().setData(uuid);
    }

}
Copyright © wueasy.com 2017-2022 all right reserved,powered by Gitbook未经允许,禁止以任何形式传播 修订时间: 2022-06-18

results matching ""

    No results matching ""